1

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.

KayV
  • 12,987
  • 11
  • 98
  • 148
  • 3
    As a side note, `return sum += p.age;` is a misleading statement. The `+=` operator modifies the variable to its left, but since `sum` is just a lambda parameter, this modification has no effect. Since only the returned sum matters, the statement should be `return sum + p.age;`, so without the printing statement, the entire lambda expression could be `(sum, p) -> sum + p.age`. Still, `.mapToInt(p -> p.age).sum()` is cleaner and more efficient than the three-arg `reduce`. – Holger Dec 01 '16 at 13:03
  • 5
    "The combiner is necessary in parallel reductions, where the input is partitioned, a partial accumulation computed for each partition, and then the partial results are combined to produce a final result." You could have found this statement in the stream package [javadoc](https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html). – Stefan Zobel Dec 01 '16 at 13:49

2 Answers2

8

Combiner gets executed only for a parallel stream.

Eugene
  • 117,005
  • 15
  • 201
  • 306
0

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

Anton Balaniuc
  • 10,889
  • 1
  • 35
  • 53