Why would the parallel stream use the combiner class, while the sequential stream would use the accumulator? Why does the parallel stream not use the accumulator?
package Streams;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
public class Collect
{
public static class Debug
{
public static void log(Object ... objects)
{
for(Object object : objects) {
System.out.println(object);
}
}
}
public static void main(String[] args)
{
parallel();
Debug.log("---------------");
sequential();
}
public static void parallel()
{
List<Integer> list = Stream.of(1,2,3,4)
.parallel()
.collect(
ArrayList::new,
(a,b)-> {
Debug.log("From accumulator",a,b);
a.add(b);
},
(a,b) -> {
Debug.log("From combiner",a,b);
a.addAll(b);
}
);
}
public static void sequential()
{
List<Integer> list = Stream.of(1,2,3,4)
.collect(
ArrayList::new,
(a,b)-> {
Debug.log("From accumulator",a,b);
a.add(b);
},
(a,b) -> {
Debug.log("From combiner",a,b);
a.addAll(b);
}
);
}
}
Here is the output of the code above:
From accumulator
[]
From accumulator
From accumulator
From accumulator
[]
[]
1
4
3
[]
2
From combiner
From combiner
[3]
[1]
[4]
[2]
From combiner
[1, 2]
[3, 4]
---------------
From accumulator
[]
1
From accumulator
[1]
2
From accumulator
[1, 2]
3
From accumulator
[1, 2, 3]
4
So again, why does the sequential stream use accumulator and the parallel stream the combiner? Can't the parallel stream use the accumulator?