问题
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