Java 8过滤器基于Map属性的Map对象列表,用于删除一些重复项 [英] Java 8 filter List of Map objects based on Map property to remove some duplicates

查看:144
本文介绍了Java 8过滤器基于Map属性的Map对象列表,用于删除一些重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个

List<Map<String, Object>> allPoints = new LinkedList<>();

每张地图都包含name键带有String值;
需要创建

Each map contains a "name" key with a String value; Need to create a

 List<Map<String, Object>> expectedPoints

列表中有重复的名称;对于这些,只想保留最后一个。

There are duplicate names in the list; for these, want to keep the last one only.

例如。如果列表有三个项目,并且第一个和第三个项目都具有值abc的name,则结果列表应该只包含原始列表中的第二个和第三个项目。

E.g. if the list has three items, and first and third items both have"name" with value "abc", the resulting list should only contain the second and third items from the original list.

推荐答案

一种方法是使用辅助地图:

One way to do it is by using an auxiliary map:

Map<String, Map<String, Object>> map = new LinkedHashMap<>(allPoints.size(), 0.75f, true);
allPoints.forEach(point -> map.put((String)point.get("name"), point));

List<Map<String, Object>> expectedPoints = new ArrayList<>(map.values());

这是因为 Map.put 要么放一个新的地图条目或用新的条目覆盖现有条目的值,因此只保留与名称相关的最后一个点。

This works because Map.put either puts a new entry to the map or overwrites the value of an existing entry with the new one, thus keeping only the last point associated with the name.

我正在创建一个使用 access-ordered LinkedHashMap java / util / LinkedHashMap.html#LinkedHashMap-int-float-boolean-rel =nofollow noreferrer>重载构造函数。这是为了保持与 allPoints 列表中相同的顺序。

I'm creating an access-ordered LinkedHashMap by using its overloaded constructor. This is to maintain the same order as in the allPoints list.

这篇关于Java 8过滤器基于Map属性的Map对象列表,用于删除一些重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆