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

标签 java java-8 java-stream

我只想使用 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/

相关文章:

ssl - TLS 2 与 JDk 8 Ciphersuites 与 MQ8?

java - 使用 forEach 遍历 varArgs

java - 基于另一个 `List` 过滤 `List`

java - Android Webview,仅在链接上启用设置长按?

java - 从接口(interface)转换为特征

java - 跳过 for 循环的某些迭代

java - 如何在 Jackson 和 Gson 之间转换日期?

java - 将两个不同的对象列表合并为一个具有共享 id 字段的对象列表

java - 为什么 Java Streams 是一次性的?

Java 8 流 - 合并映射并计算 "values"的平均值