Java Streams: Replacing groupingBy and reducing by toMap

I've asked a question before about enhancing some code, here. @Holger gives me the right response and he said that:

Whenever you find yourself using the reducing collector with groupingBy, you should check whether toMap isn’t more appropriate

It seems like a pattern ! and what he suggests me to do was just perfect.

Is this a well known pattern ? Why toMap is better than (in some cases) combining groupingBy and reducing ?


Solution 1:

This pattern became evident by experience with using both collectors. You’ll find several Q&As on Stackoverflow, where a problem could be solved with either collector, but one of them seems a better fit for the particular task.

This is a variation of the difference between Reduction and Mutable Reduction. In the first case, we use reduce on the Stream, in the second we use collect. It comes naturally, that the groupingBy collector, which takes a second Collector as argument, is the right tool when we want to apply a Mutable Reduction to the groups.

Not that obviously, the toMap collector taking a merge function is the right tool when we want to perform a classical Reduction, as that merge function has the same shape and purpose as a Reduction function, even if it is not called as such.

In practice, we note that the collectors which perform a Reduction, return an Optional, which is usually not desired when being used with groupingBy, which is the reason why toMap works more smoothly in these cases.

There are surely more patterns which become apparent while using these APIs, but collecting them in one answer is not the scope of Stackoverflow.