Why does the union function fail in a java-8 stream reduction operation?

I am trying to understand how the reduce method works in streams.

Stream.of(1,2,3,4,5,6,7).reduce(new ArrayList<>(),
(List<Integer> l, Integer a) -> {l.add(a);return l;},
(List<Integer> l1, List<Integer> l2) -> {
System.out.println("l1 is" + l1 + "l2 is " + l2);
l1.addAll(l2);
return l1;
}).forEach(System.out::println);

      

The line is System.out.println("l1 is" + l1 + "l2 is " + l2)

never printed. I can understand what is going on in (List<Integer> l, Integer a) -> {l.add(a);return l;}


Can someone explain why it is not printed? The java docs saysfunction for combining two values, which must be compatible with the accumulator function

Thanks, Amar

+3


source to share


2 answers


It is called only when the thread is parallel. In this case, the stream values ​​are split in half (recursively), each half is reduced to a list, and then the two lists must be concatenated together.



Note that the abbreviation must not mutate the values ​​(lists in this case) received as an argument. It had to return a new value. That volatile decrement (i.e. collect()

) is a much better choice in this case.

+4


source


In the java.util.stream description as below:

<U> U reduce(U identity,
          BiFunction<U, ? super T, U> accumulator,
          BinaryOperator<U> combiner);

      

The combiner function combines two partial results to create a new partial result . (A combiner is needed in parallel cuts where the input is split, the partial accumulation calculated for each section, and then the partial results are combined to get the final result.)



"necessary" implies that your stream is empty or contains only a single element in the stream, combiner

and will never be called in a parallel stream either.

So, if you want to see "l1 is" + l1 + "l2 is " + l2

, you have to run it on a parallel thread like:

//                       v--- make the stream run in parallel   
Stream.of(1,2,3,4,5,6,7).parallel().reduce(...).forEach(System.out::println);

      

+3


source







All Articles