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 ?

Naman
  • 27,789
  • 26
  • 218
  • 353
bubbles
  • 2,597
  • 1
  • 15
  • 40
  • I think it's just common sense and `Collectors` knowledge, nothing like a pattern if you ask me. – Yassin Hajaj Jul 15 '19 at 14:30
  • 8
    "Anyone can tel me how he figured this out ?" I'd guess Holger would be the best person to ask! – Andy Turner Jul 15 '19 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. – Andy Turner Jul 15 '19 at 14:50

1 Answers1

19

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.

Marc Bannout
  • 388
  • 4
  • 15
Holger
  • 285,553
  • 42
  • 434
  • 765
  • 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 May 31 '21 at 12:30
  • 4
    @Naman maybe I should start writing a blog… – Holger May 31 '21 at 12:37
  • 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. – Alexander Ivanchenko Aug 30 '22 at 10:32