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?