谁能告诉我为什么会这样,这是预期的行为还是错误
List<Integer> a = Arrays.asList(1,1,3,3);
a.parallelStream().filter(Objects::nonNull)
.filter(value -> value > 2)
.reduce(1,Integer::sum)
答案:10
但是如果我们使用 stream
而不是 parallelStream
我会得到正确和预期的 answer 7
最佳答案
reduce 的第一个参数称为“identity”而不是“initialValue”。
1
根据加法是无恒等式。 1
是乘法的恒等式。
虽然如果你想对元素求和,你需要提供 0
。
Java 使用“identity”而不是“initialValue”,因为这个小技巧可以轻松并行化 reduce
。
在并行执行中,每个线程将在流的一部分上运行 reduce,当线程完成时,它们将使用完全相同的 reduce 函数组合。
虽然它看起来像这样:
mainThread:
start thread1;
start thread2;
wait till both are finished;
thread1:
return sum(1, 3); // your reduce function applied to a part of the stream
thread2:
return sum(1, 3);
// when thread1 and thread2 are finished:
mainThread:
return sum(sum(1, resultOfThread1), sum(1, resultOfThread2));
= sum(sum(1, 4), sum(1, 4))
= sum(5, 5)
= 10
我希望你能看到,发生了什么,为什么结果不是你所期望的。
关于java - java 中的 parallelStream 中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66428662/