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

后端 未结 4 769
执念已碎
执念已碎 2021-02-01 01:23

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

I would like to pull the Contact out of a List

4条回答
  •  借酒劲吻你
    2021-02-01 02:04

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

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

    So if you have a List 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));
    

提交回复
热议问题