Use Java 8 Stream API to filter objects based on an ID and Date(使用 Java 8 Stream API 根据 ID 和日期过滤对象)
问题描述
我有一个 Contact
类,每个实例都有一个唯一的 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
类,详细说明 Contact
在某个 lastUpdated
日期执行的 action
.
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>
,它可以包含单个 Contact
的多个 Log
实例.我想根据 Log代码>对象.结果列表应包含每个
Contact
的最新 Log
实例.
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
,然后循环并获取具有最大 lastUpdated<的
Log
实例来做到这一点/code> 变量用于每个 Contact
,但这似乎可以使用 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 和日期过滤对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 Java 8 Stream API 根据 ID 和日期过滤对象
基础教程推荐
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01