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 ?
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
reduceon the Stream, in the second we usecollect. It comes naturally, that thegroupingBycollector, which takes a secondCollectoras argument, is the right tool when we want to apply a Mutable Reduction to the groups.Not that obviously, the
toMapcollector 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 withgroupingBy, which is the reason whytoMapworks 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.