Search code examples
javalambdajava-8comparatorlocaldate

Find object with max date in a list where date property is a String


Say I have an object:

public class MyObject {
     private LocalDate date;
}

In a list of these objects it's then quite easy to find the object with the newest date:

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

Is there a similarly concise way to find the object with the newest date when the date is a String instead? I need to convert the dates to LocalDates first, but I can't do something like this:

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

Solution

  • Assuming that MyObject::getDate returns a format that is acceptable for LocalDate.parse, you are nearly correct. You just need to write a lambda expression:

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

    comparing takes a Function<MyObject, T>. You are supposed to give it a method that takes a MyObject and returns something (that extends Comparable) for it to compare.

    Learn more about lambdas here.