java获取进程内的对象信息,从对象列表中获取具有max date属性的对象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 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.

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值