Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting object with max date property from list of objects Java 8

I have a class called Contact that has a Date lastUpdated; variable.

I would like to pull the Contact out of a List<Contact> that has the max lastUpdated variable.

I know that this can be done by writing a custom comparator and using Collections.max, but I was wondering if there is a way this can be done in Java 8 that does not require using a custom comparator, since I just want to pull the one with a max date in just one spot in my code, and the Contact class should not always use the lastUpdated variable for comparing instances.

like image 956
Andrew Mairose Avatar asked Jul 27 '15 15:07

Andrew Mairose


People also ask

How do I find the max date in a list of dates using Java?

map(u -> u. date) . max(Date::compareTo) . orElseThrow(() -> new IllegalArgumentException("Expected 'list' to be of size: >= 2.

How to find Min and max Date in Java?

Finding Min or Max Date. To get max or min date from a stream of dates, you can use Comparator. comparing( LocalDate::toEpochDay ) Comparator. The toEpochDay() function returns the count of days since epoch i.e. 1970-01-01.


2 Answers

Writing custom comparator in Java-8 is very simple. Use:

Comparator.comparing(c -> c.lastUpdated); 

So if you have a List<Contact> contacts, you can use

Contact lastContact = Collections.max(contacts, Comparator.comparing(c -> c.lastUpdated)); 

Or, using method references:

Contact lastContact = Collections.max(contacts, Comparator.comparing(Contact::getLastUpdated)); 
like image 87
Tagir Valeev Avatar answered Sep 20 '22 18:09

Tagir Valeev


Try the following (untested):

contacts.stream().max(Comparator.comparing(Contact::getLastUpdated)).get() 
like image 24
Puce Avatar answered Sep 19 '22 18:09

Puce