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

查看:599
本文介绍了Collectors.summingInt()vs 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()vs mapToInt()。sum()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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