Search code examples
javajava-8java-streamcollectors

Why this BiConsumer Combiner code in collect method is never reached?


In the main method,I have made a list of Person with different ages.Now when I use collect method to transform this list into a list of Persons' ages.The code in BiConsumer combiner function is never reached.

class Person {
    private int age;

    public int getAge() {
        return age;
    }
}

//second flavor of collect

ArrayList<Integer> pAges = people.stream()
                            .collect(ArrayList<Integer>::new, 
                                    (listGivenBySupplier, personObjectFromPeopleStream) -> listGivenBySupplier.add(personObjectFromPeopleStream.getAge()), 
                                    (r1, r2) -> {  //Also please explain what value is passed to r1 and r2
                                            System.out.println("r1: " + r1);
                                            System.out.println("r2: " + r2);
                                            r1.add(2222);
                                            r2.add(2211); 
                            });
System.out.println("pAges:" + pAges);

Solution

  • The combiner function is called only if you invoke the stream processing pipeline in parallel. So change it to a parallel stream and then it should reach the combiner function. So this should trigger it.

    people.parallelStream()...
    

    For an instance assume there are 2 worker threads handling this workload. Any parallel execution involves spliting the source into parts, executing them concurently and finally merging the partial results into one single result container. Each thread T1 and T2 has an associated List, such that the container is thread confined. The accumulator function adds each single element into the associated container. Upon completion of both threads T1 and T2, the partial containers should be merged into one large result container. That's where the combiner function comes into play. In a serial execution such a merging of result is not involved, hence combiner has no use there.