【问题标题】:Why is the accumulator in Stream::reduce a BiFunction and not a BinaryOperator like the combiner?为什么 Stream::reduce 中的累加器是 BiFunction 而不是 BinaryOperator 像组合器?
【发布时间】:2017-04-23 11:47:39
【问题描述】:

为什么 Stream::reduce 方法中的 accumulator 参数是 BiFunction 而不是 BinaryOperator 像 combiner 参数。

为什么它的类型是BiFunction<U, ? super T, U>?为什么T?应该是BiFunction<U, ? extends U, U>吗?

【问题讨论】:

标签: java java-8 java-stream reduce functional-interface


【解决方案1】:
<U> U reduce(U identity,
             BiFunction<U, ? super T, U> accumulator,
             BinaryOperator<U> combiner);

累加器是将Stream(其类型用T表示)的元素添加到reduce操作(其类型用U) 并返回更新的结果(也是U 类型)。

因此,您不能将其定义为 BinaryOperator,其中操作数和结果都是同一类型。

例如,您可以在reduce 调用中将BiFunction&lt;Integer,String,Integer&gt; 作为累加器 传递,该BiFunction&lt;Integer,String,Integer&gt; 应用于Stream&lt;String&gt; 并产生所有元素的长度之和。您不能为此使用 BinaryOperator&lt;Integer&gt;BinaryOperator&lt;String&gt;

另一方面,combiner 采用两个中间结果(都属于同一类型U)并将它们合并成一个类型也是U 的结果。因此可以使用BinaryOperator&lt;U&gt;(扩展BiFunction&lt;U,U,U&gt;)。

【讨论】:

  • U reduce(U identity, BiFunction accumulator, BinaryOperator combiner); ,我在问这个版本的方法,累加器是 BiFunction 并且签名应该是?超级U。docs.oracle.com/javase/8/docs/api/java/util/stream/…
  • @AhmadMoawad 这与我在回答中提到的方法签名相同。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-06
  • 2014-07-21
  • 1970-01-01
  • 2021-02-13
  • 2014-12-16
  • 2014-10-18
  • 2018-03-05
相关资源
最近更新 更多