Java Streams:替换分组并按toMap减少 [英] Java Streams: Replacing groupingBy and reducing by toMap
问题描述
我之前曾问过一个有关增强某些代码的问题, @Holger 给了我正确的答案,他说:
I've asked a question before about enhancing some code, here. @Holger gives me the right response and he said that:
每当您发现将还原剂收集器与 groupingBy,您应该检查toMap是否更合适
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.
这是众所周知的模式吗?为什么toMap
比(在某些情况下)结合groupingBy
和reducing
更好?
Is this a well known pattern ? Why toMap
is better than (in some cases) combining groupingBy
and reducing
?
推荐答案
通过使用两个收集器的经验,这种模式变得显而易见.您会在Stackoverflow上找到几个问题与解答,可以使用任一收集器解决问题,但其中一个似乎更适合特定任务.
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.
显然,采用 merge 函数的toMap
收集器是我们执行经典归约时的正确工具,因为该合并函数的形状和目的与归约函数相同,即使没有这样称呼.
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.
在实践中,我们注意到执行还原操作的收集器返回Optional
,当与groupingBy
一起使用时通常不希望这样做,这就是toMap
在这种情况下工作更顺畅的原因.
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.
使用这些API时肯定会出现更多模式,但是将它们收集在一个答案中并不是Stackoverflow的范围.
There are surely more patterns which become apparent while using these APIs, but collecting them in one answer is not the scope of Stackoverflow.
这篇关于Java Streams:替换分组并按toMap减少的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!