1

There are some questions that deal with the explanation of the Combiner in the Java Stream Reducer. However, I couldn't make it execute at all. The only result that I get is the one produced by the Accumulator. The example code is below:

public class Main {

    public static void main(String[] args) throws Exception {
        List<Person> persons =
            Arrays.asList(
                new Person("Max", 18),
                new Person("Peter", 23),
                new Person("Pamela", 23),
                new Person("David", 12));

            Integer ageSum = persons.stream()
                              .reduce(0,
                                      (sum, p) -> { 
                                        System.out.format("accumulator: sum=%s; person=%s\n", sum, p);
                                        return sum += p.age;
                                      },
                                      (sum1, sum2) -> {
                                        System.out.format("combiner: sum1=%s; sum2=%s\n", sum1, sum2);
                                        return sum1 + sum2; // (1)
                                        // return 0;        // (2)
                                      }
                                     );

            System.out.println(ageSum);
    }

}

class Person {
    String name;
    int age;

    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return name;
    }
}

I always get 76 as the result, no matter which line I leave uncommented, either (1) or (2). I don't see the output produced by System.out.format either. Not that I need this Combiner now, since I get the result I wanted - the sum of ages of all the persons, but I am curious why it does not execute. Do you have an idea how to make some use of it, i.e. how to make it actually execute?

assylias
  • 321,522
  • 82
  • 660
  • 783
gicig
  • 334
  • 3
  • 14
  • 2
    The combiner is not called in a sequential stream. Try with `persons.parallelStream()` and you should see what you expect. – assylias Nov 25 '15 at 12:26
  • 1
    See http://stackoverflow.com/questions/30015971/java8-stream-reduce-with-3-parameters-getting-transparency/30016171 and http://stackoverflow.com/questions/22808485/purpose-of-third-argument-to-reduce-function-in-java-8-functional-programming – Alexis C. Nov 25 '15 at 12:30
  • Ok, it is clear now, after I read the old question and your comments. Thanks. – gicig Nov 26 '15 at 08:06

0 Answers0