我想将列表的所有元素相乘,然后使用 Java 8 中的流将结果乘以 5。这是我的代码:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4);
int mul = numbers.stream().reduce(5, (acc, x) -> x * acc);
System.out.println(mul);
这给了我正确的结果,120。但如果我们将它更改为 parallelStream()
,那么它会生成错误的值。为什么?为什么在这种情况下并行化会产生错误的结果?修复方法是什么?
最佳答案
因为你不尊重 preconditions of the reduce()方法:
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.
对于 t 的所有值,5 * t 都不等于 t。
您应该使用 1 作为身份,并将结果乘以 5。
关于java - 使用 parallelStream().reduce() 时的错误结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42331899/