Java 8 Stream - Reduce function's combiner not getting executed [duplicate]

一曲冷凌霜 提交于 2020-01-10 04:35:21

问题


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;

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

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.


回答1:


Combiner gets executed only for a parallel stream.




回答2:


You need to use parallelStream instead of stream if you are going to use combiner



来源:https://stackoverflow.com/questions/40910619/java-8-stream-reduce-functions-combiner-not-getting-executed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!