使用Java 8获取属性的最大值 [英] Getting the max of a property using Java 8
问题描述
我想使用Stream库重写下面的代码( allPeople
是一个 List< Person>
)。
I want to rewrite the below code using the Stream library (allPeople
is a List<Person>
).
int maxYear = Integer.MIN_VALUE;
Person oldest = null;
for (Person p : allPeople) {
if (p.getDateOfDeath() > maxYear) {
oldest = p;
maxYear = p.getDateOfDeath();
}
}
我试图找到列表中最老的人人(假设Person对象上没有Age属性,这只是一个例子)。
I am trying to find the oldest person in a list of people (assuming there is no Age property on the Person object, it's just an example).
如何使用Java 8重写它?
How can I rewrite this using Java 8?
推荐答案
Person oldest = allPeople.stream().max(comparingInt(Person::getDateOfDeath)).orElse(null);
此代码创建一个人流,并在比较死亡日期时选择最大元素。这是通过使用 Comparator.comparingInt(keyExtractor)
,密钥提取器是对人员死亡日期的方法参考。
This code creates a Stream of Person and selects the max element when comparing the date of death. This is done by using Comparator.comparingInt(keyExtractor)
with the key extractor being a method-reference to the date of death of the person.
如果列表为空,则返回 null
。
If the list was empty, null
is returned.
如上所述注释,您也可以使用 Collections.max
但请注意这会抛出 NoSuchElementException
如果列表为空,那么我们需要采取在此之前照顾:
As noted in the comments, you could also use Collections.max
but note that this throws a NoSuchElementException
if the list is empty so we need to take care of that before:
Person oldest = allPeople.isEmpty() ? null : Collections.max(allPeople, comparingInt(Person::getDateOfDeath));
这篇关于使用Java 8获取属性的最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!