java123999 java123999 - 11 months ago 23
Java Question

Getting oldest DateTime in a List?

I have a list of Dog

that contain the field

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

How can I do so?


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


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, 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: