This question already has an answer here:
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.
Combiner gets executed only for a parallel stream.
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