【问题标题】:Reduce with identity combiner parallel stream使用身份组合器并行流减少
【发布时间】:2018-03-05 06:40:08
【问题描述】:
final Stream<Integer> numbers = Stream.of(5, 3, 2, 7, 3, 13, 7).parallel();

为什么下面一行的输出是7?

 numbers.reduce(1, (a, b) -> a + b, (x, y) -> x - y)); 

【问题讨论】:

  • 您违反了reduce 的合同,因为1 不是您的累加器/组合器的身份。 See javadoc
  • 为什么不是身份?请参阅此代码 - concretepage.com/java/jdk-8/java-8-stream-reduce-example (ReduceDemo3)
  • 该链接也存在一些问题,因为它违反了某些属性;请阅读文档而不是那个
  • 任何人都可以设置网页。而且有很多,除了official tutorialAPI documentation 之外,没有告诉你更多。但是您链接的那个页面是最糟糕的页面之一,只是大错特错。也许this Q&A 有帮助……

标签: java-8 java-stream reduce


【解决方案1】:

我没有查看 cmets 中的那个链接,但是文档对 identity 非常清楚,它甚至提供了一种简单的测试方法:

标识值必须是组合器函数的标识。这意味着对于所有 u,combiner(identity, u) 等于 u

所以让我们稍微简化一下你的例子:

Stream<Integer> numbers = Stream.of(3, 1).parallel();
BiFunction<Integer, Integer, Integer> accumulator = (a, b) -> a + b;

BiFunction<Integer, Integer, Integer> combiner = (x, y) -> x - y; 

    int result = numbers.reduce(
            1,
            accumulator,
            combiner);

    System.out.println(result);

假设u = 3(只是流中的一个随机元素),因此:

    int identity = 1;
    int u = 3;

    int toTest = combiner.apply(identity, u);
    System.out.println(toTest == identity); // must be true, but is false

即使您认为将身份替换为zero,也可以;文档提出了另一个论点:

另外,combiner 函数必须与 accumulator 函数兼容;对于所有 u 和 t,必须满足以下条件:

 combiner.apply(u, accumulator.apply(identity, t)) == accumulator.apply(u, t)

你可以做同样的测试:

int identity = 0;
int u = 3;
int t = 1;

boolean associativityRespected = 
     combiner.apply(u, accumulator.apply(identity, t)) == accumulator.apply(u, t);
System.out.println(associativityRespected); // prints false

【讨论】:

  • 或者换句话说,在reduce 中做两件完全不同的事情,比如(a,b)-&gt;a+b(x,y)-&gt;x-y,是无稽之谈。此外,(x, y) -&gt; x - y 本身已经违反了合同,因为它没有关联性。令人印象深刻的是,该网页的作者设法在一个示例中放入了多少错误的东西......
  • @Holger 我只能说能够将一些代码移植到 java-8 (并且经理完全不知道 它确实需要安静很多时间来了解这些东西),在网上找到一个好的资源真的很难。所以,是的,我不能同意更多。很明显,你在附近。
  • 在你的第一个测试中,我猜你的意思是System.out.println(toTest == u);
猜你喜欢
  • 2022-08-21
  • 2014-12-16
  • 2016-08-18
  • 2021-01-01
  • 2020-01-19
  • 2017-05-23
  • 1970-01-01
  • 1970-01-01
  • 2018-11-11
相关资源
最近更新 更多