Getting the max of a property using Java 8

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-01 08:40:41

问题


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();
    }
}

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).

How can I rewrite this using Java 8?


回答1:


Person oldest = allPeople.stream().max(comparingInt(Person::getDateOfDeath)).orElse(null);

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.

If the list was empty, null is returned.

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));


来源:https://stackoverflow.com/questions/33713876/getting-the-max-of-a-property-using-java-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!