Spacejockey
Spacejockey

Reputation: 398

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

Upvotes: 3

Views: 2816

Answers (2)

ETO
ETO

Reputation: 7279

You can also create an utility method and then use it in functional style:

static <T> Function<T, LocalDate> parsingDate(Function<T, String> extractor){
    return t -> LocalDate.parse(extractor.apply()));
}

MyObject newest = max(myObjectList, comparing(parsingDate(MyObject::getDate))); 

Upvotes: 0

Sweeper
Sweeper

Reputation: 271030

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.

Upvotes: 3

Related Questions