Skip to content
Advertisement

How do you call a method from within a Collector in Java 8 Streaming?

I have a bit of code that is working functionally as I want it to:

JavaScript

For sake of argument the helper class method is:

JavaScript

I would like to do this with a collector instead so I wanted to do this …

JavaScript

But obviously this fails because it is not doing the helper class lookup and so rather than returning a map of <Florest, Flowers> it is returning <String, Flowers>

This fails though :

JavaScript

Can anyone tell me how I should call the lookup methods (FlorestHelperClass.florestTypeForKey) in the collector? Is it possible?

Advertisement

Answer

Collectors.toMap requires two functions creating a key and value respectively from the value passed into the collect method. Therefore you can do this:

JavaScript

The last lambda expression can be replaced with FlorestFranchised::getFlowers.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement