从对象列表中获取具有最大日期属性的对象 Java 8

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31657036/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 11:22:50  来源:igfitidea点击:

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

javacollectionsjava-8

提问by Andrew Mairose

I have a class called Contactthat has a Date lastUpdated;variable.

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

I would like to pull the Contactout of a List<Contact>that has the max lastUpdatedvariable.

我想ContactList<Contact>具有 maxlastUpdated变量的 a中取出。

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 Contactclass should not always use the lastUpdatedvariable for comparing instances.

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

采纳答案by Alexis C.

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

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

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

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

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

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

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

回答by Tagir Valeev

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

在 Java-8 中编写自定义比较器非常简单。用:

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

So if you have a List<Contact> contacts, you can use

所以如果你有一个List<Contact> contacts,你可以使用

Contact lastContact = Collections.max(contacts, Comparator.comparing(c -> c.lastUpdated));

Or, using method references:

或者,使用方法引用:

Contact lastContact = Collections.max(contacts, Comparator.comparing(Contact::getLastUpdated));

回答by M. Shaw

Use List<T>.stream().max(Comparator<T>).get()after you defined a suitable Comparator.

使用List<T>.stream().max(Comparator<T>).get()您定义的合适后Comparator

回答by Puce

Try the following (untested):

尝试以下(未经测试):

contacts.stream().max(Comparator.comparing(Contact::getLastUpdated)).get()