java中parallelStream中的错误

问题描述

谁能告诉我为什么会发生这种情况,这是预期的行为还是错误

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),4))
  = sum(5,5)
  = 10

我希望你能看到会发生什么以及为什么结果不是你所期望的。