Java Streams:替换分组并按toMap减少 [英] Java Streams: Replacing groupingBy and reducing by toMap

查看:82
本文介绍了Java Streams:替换分组并按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比(在某些情况下)结合groupingByreducing更好?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆