Java 8 filter List of Map objects based on Map property to remove some duplicates

别等时光非礼了梦想. 提交于 2020-01-01 06:45:08

问题


Have a

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

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.

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.


回答1:


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());

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.

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




回答2:


In case you have the constraint on one or more key-value pairs and flexible to use a Set, write your own Comparator and use descendingIterator on LinkedList and write to TreeSet. See code below:

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

        Set<Map<String, Object>> expectedPoints = new TreeSet<>((objectMap1, objectMap2) ->
                objectMap2.get("name").equals(objectMap1.get("name")) ? 0 : -1
        );

        allPoints.descendingIterator().forEachRemaining(expectedPoints::add);


来源:https://stackoverflow.com/questions/49196608/java-8-filter-list-of-map-objects-based-on-map-property-to-remove-some-duplicate

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!