gpt4 book ai didi

java - 如何仅使用 reduce 在列表中找到最小值?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:32:37 25 4
gpt4 key购买 nike

我只想使用 reduceList<Integer> 中找到最小值.这是我首先想到的:

List<Integer> lst;
//init
//assuming it's not empty
lst.stream().reduce(lst.get(0), (x, y) -> x.compareTo(y) <= 0 ? x : y);

但在 the contract 那个方法说:

The identity value must be an identity for the accumulator function. This means that for all t, accumulator.apply(identity, t) is equal to t. The accumulator function must be an associative function.

所以,唯一可能的identity保值累加器合约(x, y) -> x.compareTo(y) <= 0 ? x : y是最大的。因此,我们遇到了某种先有鸡还是先有蛋的问题。

如何解决保留所有合约?

最佳答案

使用 Integer.MAX_VALUE .其他一切都将小于或等于那个,所以它满足 min(identity, t) == t 的契约(Contract)。对于所有 t .

进一步调查后,我认为您不需要身份。有一个 reduce仅将函数作为参数,http://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#reduce-java.util.function.BinaryOperator- .这将返回 Optional<Integer>而不是 Integer .我认为,原因是该方法必须处理流中没有元素的情况。在这种情况下,Optional<Integer>版本将返回一个空值;而需要 identity 的版本并返回 Integer将返回标识值(类似于数学中的方式,如果您添加一组数字并且它是空的,您应该得到 0,如果您乘以一组数字并且它是空的,您应该得到 1)。所以如果你知道你的列表是非空的,你实际上应该能够写

lst.stream().reduce((x, y) -> x.compareTo(y) <= 0  ? x : y).get();

关于java - 如何仅使用 reduce 在列表中找到最小值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37246844/

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