本文介绍了Java Streams:替换 groupingBy 并减少 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是否更合适

这似乎是一种模式!他建议我做的事情非常完美.

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.

这是减少可变归约.在第一种情况下,我们在 Stream 上使用 reduce,在第二种情况下,我们使用 collect.很自然,groupingBy 收集器以第二个 Collector 作为参数,当我们想对组应用可变归约时,它是正确的工具.

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.

在实践中,我们注意到执行 Reduction 的收集器返回一个 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:替换 groupingBy 并减少 toMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 02:22