gpt4 book ai didi

java - Java 8 函数式编程中 'reduce' 函数的第三个参数的用途

转载 作者:IT老高 更新时间:2023-10-28 21:08:55 24 4
gpt4 key购买 nike

在 Java 8 流中调用 'reduce' 的第三个参数在什么情况下?

下面的代码尝试遍历字符串列表并将每个字符串的第一个字符的代码点值相加。最终 lambda 返回的值似乎从未被使用过,如果您插入 println,它似乎永远不会被调用。该文档将其描述为“组合器”,但我找不到更多详细信息...

int result =
data.stream().reduce(0, (total,s) -> total + s.codePointAt(0), (a,b) -> 1000000);

最佳答案

你说的是this function ?

reduce <U> U reduce(U identity,
BiFunction<U,? super T,U> accumulator,
BinaryOperator<U> combiner)

Performs a reduction on the elements of this stream, using the provided identity, accumulation and combining functions. This is equivalent to:

 U result = identity;
for (T element : this stream)
result = accumulator.apply(result, element)
return result;

but is not constrained to execute sequentially. The identity value must be an identity for the combiner function. This means that for all u, combiner(identity, u) is equal to u. Additionally, the combiner function must be compatible with the accumulator function; for all u and t, the following must hold:

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

This is a terminal operation.

API Note: Many reductions using this form can be represented more simply by an explicit combination of map and reduce operations. The accumulator function acts as a fused mapper and accumulator, which can sometimes be more efficient than separate mapping and reduction, such as when knowing the previously reduced value allows you to avoid some computation. Type Parameters: U - The type of the result Parameters: identity - the identity value for the combiner function accumulator - an associative, non-interfering, stateless function for incorporating an additional element into a result combiner - an associative, non-interfering, stateless function for combining two values, which must be compatible with the accumulator function Returns: the result of the reduction See Also: reduce(BinaryOperator), reduce(Object, BinaryOperator)

我假设它的目的是允许并行计算,所以我的猜测是它仅在并行执行缩减时使用。如果按顺序执行,则无需使用combiner。我不确定——我只是根据文档注释“[...] 不限于按顺序执行”以及注释中提到的“并行执行”的许多其他内容进行猜测。

关于java - Java 8 函数式编程中 'reduce' 函数的第三个参数的用途,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22808485/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com