java123999 java123999 - 1 year ago 99
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;

Answer Source

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:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download