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

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

问题描述

我有一个名为 Contact 的类,它有一个 Date lastUpdated; 变量.

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

我想从具有最大 lastUpdated 变量的 List 中提取 Contact.

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

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

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.

推荐答案

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

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

因此,每当您想通过 lastUpdated 属性比较多个实例时,您都必须提供自定义比较器,因为这意味着该类在默认情况下无法与此字段进行比较.

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);

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

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.

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

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