Java – Find the object with the largest date in a list where the date attribute is a string

Find the object with the largest date in a list where the date attribute is a string… here is a solution to the problem.

Find the object with the largest date in a list where the date attribute is a string

Let’s say I have an object:

public class MyObject {
     private LocalDate date;
}

In the list of these objects, it is easy to find the object with the latest date:

MyObject newest = Collections.max(myObjectList, Comparator.comparing(MyObject::getDate));

Is there a similarly concise way to find an object with the latest date when the date is a string? I need to convert the date to LocalDates first, but I can’t do that :

MyObject newest = Collections.max(myObjectList, Comparator.comparing(LocalDate.parse(MyObject::getDate)));

Solution

Assuming MyObject::getDate returns an acceptable format for LocalDate.parse, you’re pretty much right. You just need to write a lambda expression:

Comparator.comparing(o -> LocalDate.parse(o.getDate()))

Comparing requires Function<MyObject, T> You should give it a method that accepts MyObject. And return something (extended comparable) for comparison.

Learn more about lambda here

Related Problems and Solutions