Reputation: 1081
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?
Upvotes: 4
Views: 553
Reputation: 691755
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.
Upvotes: 14