Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong result when using parallelStream().reduce()

I want to multiply all elements of a list together and then multiply that result by 5 using streams in Java 8. This is my code:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4);
int mul = numbers.stream().reduce(5, (acc, x) -> x * acc);
System.out.println(mul);

This gives me the correct result, 120. But if we change it to parallelStream() then it generates the wrong value. Why? Why does parallelization produce the wrong result in this case? And what is the fix?

like image 761
Soumya Kanti Naskar Avatar asked Dec 10 '22 12:12

Soumya Kanti Naskar


1 Answers

Because you're not respecting the preconditions of the reduce() method:

The identity value must be an identity for the accumulator function. This means that for all t, accumulator.apply(identity, t) is equal to t.

5 * t is not equal to t for all values of t.

You should use 1 as the identity, and multiply the result by 5.

like image 194
JB Nizet Avatar answered Dec 24 '22 11:12

JB Nizet