Java mapToInt与带有地图的Reduce [英] Java mapToInt vs Reduce with map

查看:153
本文介绍了Java mapToInt与带有地图的Reduce的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读reduce,发现有3个参数的版本可以执行map reduce,如下所示:

I've been reading up on reduce and have just found out that there is a 3 argument version that can essentially perform a map reduce like this:

String[] strarr = {"abc", "defg", "vwxyz"};

System.out.println(Arrays.stream(strarr).reduce(0, (l, s) -> l + s.length(), (s1, s2) -> s1 + s2));

但是,我看不到带有reduce的mapToInt的优势.

However I can't see the advantage of this over a mapToInt with a reduce.

System.out.println(Arrays.stream(strarr).mapToInt(s -> s.length()).reduce(0, (s1, s2) -> s1 + s2));

两者都给出正确的答案12,并且看起来似乎并行工作都很好.

Both produce the correct answer of 12, and both appear to work fine in parallel.

一个比另一个好吗?如果是,为什么?

Is one better than the other, and if so, why?

推荐答案

一个比另一个好吗?如果是,为什么?

Is one better than the other, and if so, why?

使用第一种reduce方法会产生隐匿的装箱费用.

With the first reduce approach there’s an insidious boxing cost.

mapToInt.reduce(...)方法可以避免这种情况.

The mapToInt.reduce(...) approach avoids that.

所以,这个想法是,如果您对求和感兴趣,average等人会使用原始流特化,因为它们的效率更高.

So, the idea is if you're interested in summation, average et al just use the primitive stream specializations as they're more efficient.

顺便说一句,代码:

Arrays.stream(strarr).mapToInt(s -> s.length()).reduce(0, (s1, s2) -> s1 + s2)

可以简化为:

Arrays.stream(strarr).mapToInt(s -> s.length()).sum();

这篇关于Java mapToInt与带有地图的Reduce的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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