Why is the combiner function reduction operation not performed in the java-8 stream?

See English answers > java 8 stream – reduce function's combiner not getting executed

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);

System. out. The println ("L1 is" L1 "and L2 is" L2 ") line will never print. I can understand what happened (list < integer > L, integer a) – > {l.add (a); return L;} Can someone explain why not print? Java docs represents a function that combines two values. It must be compatible with the accumulator function

Thank you, Amar

Solution

It is only called when the stream is parallel In this case, the stream value is divided into two halves (recursively), each half is reduced to a list, and then the two lists must be combined

Note that the reduction should not change the value received as a parameter (in this case, a list) It should return a new value In this case, this is a variable reduction (i.e. collect ()) and is a better choice

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>