以下是 Oracle Java 13 文档:
U reduce (U identity,
BiFunction accumulator,
BinaryOperator combiner)
参数:
identity - 组合器函数的标识值
accumulator - 一个关联的、无干扰的、无状态的函数,用于将附加元素合并到结果
组合器中 - 一个关联的、非用于组合两个值的干扰无状态函数,必须与累加器函数兼容
https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/stream/Stream.html#reduce(U,java.util.function.BiFunction,java. util.function.BinaryOperator)
首先,我知道运算符的结合性意味着 (a op b) op c == a op (b op c)。维基百科说关联属性是一些二元运算的属性。二元运算表示 f:S × S → S。
这是我的问题:如果累加器函数的域不是 S x S 而是 S x T,那么累加器怎么会是关联的?
例如,
int length = asList("str1", "str2").stream()
.reduce(0, (accumulatedInt, str ) -> accumulatedInt + str.length(),
(accumulatedInt, accumulatedInt2) -> accumulatedInt + accumulatedInt2);
在这种情况下,累加器是(accumulatedInt, str ) -> accumulatedInt + str.length()
关联的,它不是关联的。它需要两种不同类型的参数。怎么会是 (a op b) op c == a op (b op c)。java文档中“累加器必须是关联的”是什么意思?
在这种reduce
方法的情况下, 的结合性accumulator
可以用accumulator
和combiner
函数(除了identity
值)来表示。
例如,假设您Stream
有元素 t1、t2 和 t3。
您可以将 t1 和 t2 添加到中间结果,然后将 t3 添加到该结果 - 这相当于(t1 op t2) op t3
.
或者,您可以将 t2 和 t3 添加到中间结果,然后将 t1 添加到该结果 - 这相当于t1 op (t2 op t3)
.
关联性意味着两种情况下的最终结果必须相同。
写这个是累加器和组合器函数的术语,它看起来像这样(我没有写显式方法调用,因为在我看来这会不太可读):
((identity <accumulator> t1) <accumulator> t2) <accumulator> t3 ==
(identity <accumulator> t1) <combiner> ((identity <accumulator> t2) <accumulator> t3)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句