javajava-8java-streamreducecombiners

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


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.


Solution

  • Combiner gets executed only for a parallel stream.