Java 8 Stream - Reduce函数的组合器没有被执行 [英] Java 8 Stream - Reduce function's combiner not getting executed

查看:127
本文介绍了Java 8 Stream - Reduce函数的组合器没有被执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个带有三个参数的简单reduce方法。身份,累加器和组合器。
这是我的代码......

I am using a simple reduce method with three arguments viz. identity, accumulator and combiner. Here is my code...

Integer ageSumComb = persons
            .stream()
            .reduce(0,
                (sum, p) -> {
                    System.out.println("Accumulator: Sum= "+ sum + " Person= " + p);
                    return sum += p.age;
                },
                (sum1, sum2) -> {
                    System.out.format("Combiner: Sum1= " + sum1 + " Sum2= "+ sum2);
                    return sum1 + sum2;

但是发生的事情是Combiner是没有得到执行。我没有得到这背后的原因。
这是我的输出..

But what is happening is the Combiner is not getting executed. I am not getting the reason behind this. Here is my output..

Accumulator: Sum= 0 Person= Max
Accumulator: Sum= 18 Person= Peter
Accumulator: Sum= 41 Person= Pamela
Accumulator: Sum= 64 Person= David
Accumulator: Sum= 76 Person= Pam

然而,没有编译错误,也没有异常,我的输出是ex行为正确,与我的预期相同。但是没有得到组合器未执行的原因。

However, There was no compilation error and no exception and my output is exactly right, the same what i had expected. But did not get why the combiner not executed.

推荐答案

组合器仅针对并行流执行。

Combiner gets executed only for a parallel stream.

这篇关于Java 8 Stream - Reduce函数的组合器没有被执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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