Collectors.summingInt() 与 mapToInt().sum() [英] Collectors.summingInt() vs mapToInt().sum()

查看:27
本文介绍了Collectors.summingInt() 与 mapToInt().sum()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当你想对一个流中的一个整数值求和时,有两种主要的方法:

When you want to sum an integer value from a stream, there are two main ways of doing it:

ToIntFunction<...> mapFunc = ...
int sum = stream().collect(Collectors.summingInt(mapFunc))

int sum = stream().mapToInt(mapFunc).sum()

第一个涉及装箱返回的整数 &拆箱,但第二步需要额外的步骤.

The first involves boxing the returned integer & unboxing it, but there's an extra step involved in the second.

哪个更高效/更清晰?

推荐答案

您正在查看两个截然不同的用例的交集.使用 mapToInt(…) 允许您在终端操作之前链接其他 IntStream 操作.相比之下,Collectors.summingInt(…) 可以与其他收集器结合使用,例如在 groupingBy 收集器中用作下游收集器.对于这些用例,使用哪个是毫无疑问的.

You are looking at the intersection of two otherwise distinct use cases. Using mapToInt(…) allows you to chain other IntStream operations before the terminal operation. In contrast, Collectors.summingInt(…) can be combined with other collectors, e.g. used as downstream collector in a groupingBy collector. For these use cases, there is no question about which to use.

在您的特殊情况下,当您首先不链接更多操作或处理收集器时,这两种方法之间没有根本区别.尽管如此,使用更具可读性的方法还是有道理的.通常,当流上有一个预定义的操作做同样的事情时,你不使用收集器.当您可以使用 .reduce(…) 时,您不会使用 collect(Collectors.reducing(…)),对吗?

In your special case, when you are not chaining more operations nor dealing with collectors in the first place, there is no fundamental difference between these two approaches. Still, using the one which is more readable has a point. Usually, you don’t use a collector, when there is a predefined operation on the stream doing the same. You wouldn’t use collect(Collectors.reducing(…)) when you can just use .reduce(…), would you?

不仅是 mapToInt(mapFunc).sum() 的缩写,它还遵循通常的从左到右的顺序来处理概念上发生的事情,首先转换为 int,然后将这些 int 相加.我认为这证明比 .collect(Collectors.summingInt(mapFunc)) 更喜欢这个替代方案是合理的.

Not only is mapToInt(mapFunc).sum() shorted, it also follows the usual left-to-right order for what happens conceptionally, first convert to an int, then sum these ints up. I think this justifies preferring this alternative over .collect(Collectors.summingInt(mapFunc)).

这篇关于Collectors.summingInt() 与 mapToInt().sum()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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