gpt4 book ai didi

Java 8 计算最小值

转载 作者:行者123 更新时间:2023-12-04 20:48:16 24 4
gpt4 key购买 nike

我正在练习 Java 8。我不明白为什么这个方法总是返回 0,或者更好的标识值:

public static Integer getMinAge(List<Person> peopleList) {
return peopleList.stream().mapToInt(Person::getAge).reduce(0, Integer::min);
}

令人惊讶的是,Integer::max 方法返回了正确的值。我在这里做错了什么?

最佳答案

因为 age > 0 和 identity == 0 那么 Integer.min(identity,age) 总是返回 0。

使用 IntStream.reduce(IntBinaryOperator)

public static Integer getMinAge(List<Person> peopleList) {
return peopleList.stream().mapToInt(Person::getAge)
.reduce(Integer::min).orElse(0);
}

使用 IntStream.min()

public static Integer getMinAge(List<Person> peopleList) {
return peopleList.stream().mapToInt(Person::getAge)
.min().orElse(0);
}

关于Java 8 计算最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43028806/

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