[英]Java 8 Stream API Filtering
I have a collection of objects, with the following type: 我有以下类型的对象的集合:
{
String action_name; //add or delete
long action_time;
String action_target;
}
Need to get the latest merged operation on each action_target 需要获取每个action_target上的最新合并操作
Sample input data: 样本输入数据:
[add|1001|item1, add|1002|item2, delete|1003|item1, add|1004|item1]
Expected result: 预期结果:
[add|1002|item2, add|1004|item1]
Sample input data: 样本输入数据:
[add|1001|item1, add|1002|item2, delete|1003|item1]
Expected result: 预期结果:
[add|1002|item2]
Sample input data: 样本输入数据:
[delete|1001|item1, add|1002|item2, add|1003|item1]
Expected result: 预期结果:
[add|1002|item2, add|1003|item1]
Is this approachable using Java8 stream APIs? 使用Java8流API可以做到这一点吗? Thanks. 谢谢。
You want to group by one criteria (the action_target
) combined with reducing the groups to the maximum of their action_time
values: 您想按一个条件( action_target
)分组,同时将组减少到最大 action_time
值:
Map<String,Item> map=items.stream().collect(
Collectors.groupingBy(item->item.action_target,
Collectors.collectingAndThen(
Collectors.maxBy(Comparator.comparing(item->item.action_time)),
Optional::get)));
This returns a Map<String,Item>
but, of course, you may call values()
on it to get a collection of items. 这将返回Map<String,Item>
但是,当然,您可以在其上调用values()
以获取项目集合。
Beautified with static import
s, the code looks like: 用static import
s进行美化,代码如下所示:
Map<String,Item> map=items.stream().collect(groupingBy(item->item.action_target,
collectingAndThen(maxBy(comparing(item->item.action_time)), Optional::get)));
Your additional request of taking care of idempotent "add"
and follow-up "delete"
actions can be simplified to “remove items whose last action is "delete"
” which can be implemented just by doing that after collecting using a mutable map: 您对处理幂等"add"
和后续"delete"
操作的附加请求可以简化为“删除最后一个操作为"delete"
”,只需在使用可变映射进行收集之后执行此操作即可实现:
HashMap<String,Item> map=items.stream().collect(groupingBy(
item->item.action_target, HashMap::new,
collectingAndThen(maxBy(comparing(item->item.action_time)), Optional::get)));
map.values().removeIf(item->item.action_name.equals("delete"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.