我只想使用 reduce
在 List<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 tot
. 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/