问题描述
我有一个联系
类,每个实例都有一个唯一的 contactId
。
I have a Contact
class, for which each instance has a unique contactId
.
public class Contact {
private Long contactId;
... other variables, getters, setters, etc ...
}
一个 Log
类详细说明行动
由联系人执行
在某个 lastUpdated
日期。
And a Log
class that details an action
performed by a Contact
on a certain lastUpdated
date.
public class Log {
private Contact contact;
private Date lastUpdated;
private String action;
... other variables, getters, setters, etc ...
}
现在,在我的代码中,我有一个 List< Log>
,它可以包含多个 Log
个实例单个联系
。我想根据<$ c $过滤列表,为每个联系
只包含一个 Log
实例c> Log
对象中的lastUpdated 变量。结果列表应包含每个联系人
的最新日志
实例。
Now, in my code I have a List<Log>
that can contain multiple Log
instances for a single Contact
. I would like to filter the list to include only one Log
instance for each Contact
, based on the lastUpdated
variable in the Log
object. The resulting list should contain the newest Log
instance for each Contact
.
我可以通过创建一个 Map< Contact,List< Log>>
,然后循环并获取 Log
每个联系
的最大 lastUpdated
变量的实例,但这似乎可以做得更简单使用Java 8 Stream API。
I could do this by creating a Map<Contact, List<Log>>
, then looping through and getting the Log
instance with max lastUpdated
variable for each Contact
, but this seems like it could be done much simpler with the Java 8 Stream API.
如何使用Java 8 Stream API实现此目的?
How would one accomplish this using the Java 8 Stream API?
推荐答案
你可以链接几个收藏家来获得你想要的东西:
You can chain several collectors to get what you want:
import static java.util.stream.Collectors.*;
List<Log> list = ...
Map<Contact, Log> logs = list.stream()
.collect(groupingBy(Log::getContact,
collectingAndThen(maxBy(Comparator.comparing(Log::getLastUpdated)), Optional::get)));
这篇关于使用Java 8 Stream API根据ID和日期过滤对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!