Reputation: 31235
I have a class Person
defined with those attributes :
private String name;
private String surname;
private Date birthday;
I want to get the max of the birthdays in a Collection<Person>
.
In Java 7, without external libraries, I would do it like this :
public Date maxAgeJava7(Collection<Person> persons) {
Date max = null;
for (Person person : persons) {
if (max == null || person.getBirthday().after(max)) {
max = person.getBirthday();
}
}
return max;
}
Now, In Java 8, it is possible to write it like this :
public Date maxAgeJava8(Collection<Person> persons) {
return persons.stream().map(Person::getBirthday).max((Date d1, Date d2)-> d1.compareTo(d2)).get();
}
This is far better BUT I don't like this part :
(Date d1, Date d2)-> d1.compareTo(d2)
As Date implements Comparable
, is there a way to tell Java to use the compareTo()
method, without having to explicitly write it?
Upvotes: 1
Views: 119
Reputation: 93872
max
requires a Comparator
as parameter.
I think the shortest thing you can do is to call the method compareTo
using method reference.
public Date maxAgeJava8(Collection<Person> persons) {
return persons.stream().map(Person::getBirthday).max(Date::compareTo).get();
}
Also note that you don't need to use a Stream
to accomplish this. You could simply use Collections.max
providing a custom comparator:
public Date maxAgeJava8(Collection<Person> persons) {
return Collections.max(persons, Comparator.comparing(Person::getBirthday)).getBirthday();
}
Upvotes: 5