从对象列表中获取具有max date属性的对象Java 8 [英] Getting object with max date property from list of objects Java 8

查看:988
本文介绍了从对象列表中获取具有max date属性的对象Java 8的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为类有 Date lastUpdated; 变量。



我想从列表<联系> 中取出联系人最大 lastUpdated 变量。



我知道这可以通过编写一个自定义比较器并使用 Collections.max ,但我想知道是否有一种方法,这可以在Java 8中完成,不需要使用自定义比较器,因为我只是想拉一个最大日期只在我的代码中的一个位置,并且 Contact 类不应该总是使用 lastUpdated 变量来比较实例。

解决方案


并且Contact类不应该总是使用lastUpdated变量
来比较实例


因此,当您想要通过 lastUpdated 比较多个实例时, code>属性,因为它意味着这个类在默认情况下与此字段不可比。

 比较器< Contact> cmp = Comparator.comparing(Contact :: getLastUpdated); 

如你所知你可以使用 Collections.max 或Stream API根据此字段获取最大实例,但您不能避免编写自定义比较器。


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.

解决方案

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<Contact> 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.

这篇关于从对象列表中获取具有max date属性的对象Java 8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆