java123999 java123999 - 7 months ago 8
Java Question

Getting oldest DateTime in a List?

I have a list of Dog

Entities
that contain the field
"Birthday".


I would like to have a method in the entity class that returns only the oldest
DateTime
in the list.

How can I do so?

Entity:

@Entity
@Table(name = "DOG")
public class Dog
{

//some other fields

@Column(name = "BIRTHDAY")
@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
private DateTime birthday;


Example of List:

private List<Dog> dogList;

Answer

In Java 8 using a stream and a lambda to create the comparator, then get the birthday from the Optional:

public static DateTime getOldestDogsBirthday(final Collection<? extends Dog> dogs) {
    return dogs.stream().min((d1, d2) -> d1.getBirthday().compareTo(d2.getBirthday())).get().getBirthday();
}

Update: Even more concise example based on suggestion in comments to use getBirthday as a method reference passed into Comparator.comparing:

return dogs.stream().min(Comparator.comparing(Dog::getBirthday)).get().getBirthday();
Comments