Java Streams:替换 groupingBy 和 reduce by toMap

Java Streams: Replacing groupingBy and reducing by toMap(Java Streams:替换 groupingBy 和 reduce by toMap)

本文介绍了Java Streams:替换 groupingBy 和 reduce 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 比(在某些情况下)结合 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.很自然,当我们想要对组应用可变缩减时,将第二个 Collector 作为参数的 groupingBy 收集器是正确的工具.

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 和 reduce by toMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Java Streams:替换 groupingBy 和 reduce by toMap

基础教程推荐