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

后端 未结 4 882
执念已碎
执念已碎 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

    and the Contact class should not always use the lastUpdated variable for comparing instances

    So you will have to provide a custom comparator whenever you want to compare multiple instances by their lastUpdated property, as it implies that this class is not comparable by default with this field.

    Comparator cmp = Comparator.comparing(Contact::getLastUpdated);
    

    As you know you can either use Collections.max or the Stream API to get the max instance according to this field, but you can't avoid writing a custom comparator.

提交回复
热议问题