[英]Getting object with max date property from list of objects Java 8
I have a class called Contact
that has a Date lastUpdated;
我有一个名为
Contact
的类,它有一个Date lastUpdated;
variable.多变的。
I would like to pull the Contact
out of a List<Contact>
that has the max lastUpdated
variable.我想从具有最大
lastUpdated
变量的List<Contact>
中拉出Contact
。
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.我知道这可以通过编写自定义比较器并使用
Collections.max
来完成,但我想知道是否有一种方法可以在不需要使用自定义比较器的 Java 8 中完成,因为我只想拉一个在我的代码中只有一个位置具有最大日期,并且Contact
类不应该总是使用lastUpdated
变量来比较实例。
Writing custom comparator in Java-8 is very simple.在 Java-8 中编写自定义比较器非常简单。 Use:
用:
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));
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 lastUpdated
property, 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.max
or 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 根据此字段获取最大实例,但您无法避免编写自定义比较器。
尝试以下(未经测试):
contacts.stream().max(Comparator.comparing(Contact::getLastUpdated)).get()
在定义合适的Comparator
后使用List<T>.stream().max(Comparator<T>).get()
。
Since you wanted to do it using java 8 lambdas, use this (assuming you have List<Contact> contacts
):由于您想使用 java 8 lambdas 来完成它,请使用它(假设您有
List<Contact> contacts
):
Contact latest = contacts.stream()
.sorted(Comparator.<Contact, Date>comparing(contact-> contact.getLastUpdated(), Comparator.reverseOrder()))
.findFirst().get();
You can customize this comparator quite easily by simply appending further comparator.您可以通过简单地附加更多比较器来轻松自定义此比较器。 So the code is easily modifiable.
所以代码很容易修改。
List<Contact> sortedContacts = contacts.stream()
.sorted(Comparator.<Contact, Date>comparing(contact-> contact.getLastUpdated(), Comparator.reverseOrder())
.thenComparing(contact -> contact.getAge()))
.collect(Collectors.toList());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.