Hi,
See if the explanation below makes sense for the results you are seeing.
Consider this method:
T reduce(T identity, BinaryOperator<T> accumulator)
This method on a parallel stream uses the accumulator as a combiner (i.e. for combining partial results).
The accumulator and the combiner must satisfy the following relationship for any t1 and t2:
combiner.apply(t1, accumulator.apply(identity, t2)) == accumulator.apply(t1, t2)
In the code:
System.out.println(List.of(1,2,3,4,5)
.parallelStream()
.reduce(0, (a,b) -> (a-b)));
The identity value is 0 and the accumulator is (a,b) -> (a-b).
For t1 = 1 and t2 = 2:
1 - (0-2) != 1 - 2
3 != -1
The above relationship does not hold for elements in the stream.
Not surprising, this method does not compute the correct result when used on a sequential stream.
Now consider this method:
<W> W reduce(W identity, BiFunction<W,? super T,W> accumulator, BinaryOperator<W> combiner)
In the code:
System.out.println(List.of(1,2,3,4,5)
.parallelStream()
.reduce(0, (a, b) -> (a - b)), (x, y) -> x + y));
The identity value is 0, the accumulator is (a, b) -> (a - b) and the combiner is (x, y) -> x + y).
For t1 = 1 and t2 = 2:
1 + (0-2) = 1 - 2
-1 = -1
The above relationship holds for all elements in the stream.
The result is computed correctly for parallel streams.