1

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);
Michał Krzywański
  • 15,659
  • 4
  • 36
  • 63
Codeninja
  • 55
  • 1
  • 6
  • you could just use stream().map() as next: List ages = people.stream().map(Person::getAge).collect(Collectors.toList()); – lub0v Jul 31 '19 at 05:02
  • @lub0v I know that, but I want to use the other flavor of collect() with supplier, biconsumer accumulator and biconsumer combiner. – Codeninja Jul 31 '19 at 05:21
  • 2
    here is the same question, btw https://stackoverflow.com/questions/29959795/how-does-combiner-in-stream-collect-method-work-in-java-8 – lub0v Jul 31 '19 at 05:27

1 Answers1

1

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.

Ravindra Ranwala
  • 20,744
  • 6
  • 45
  • 63