13

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 ?

3
  • I think it's just common sense and Collectors knowledge, nothing like a pattern if you ask me. Commented Jul 15, 2019 at 14:30
  • 8
    "Anyone can tel me how he figured this out ?" I'd guess Holger would be the best person to ask! Commented Jul 15, 2019 at 14:32
  • 1
    @ElmaCherb commenting again on that answer (using @Holger) would notify him directly. It was several weeks ago, so he is unlikely to revisit the question unless prompted. Commented Jul 15, 2019 at 14:50

1 Answer 1

20
+350

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. I have read this time and time again. How about detailing those 'more patterns' in a blog or sharing links to some existing articles?
@Naman maybe I should start writing a blog…
Indeed, in some cases, it might not seem very obvious that toMap with a merge function is the right tool. But it really makes a difference in terms of readability. Very instructive observation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.