Java 8 filter List of Map objects based on Map pro

2020-06-25 04:13发布

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.

标签: java java-8
2条回答
Fickle 薄情
2楼-- · 2020-06-25 05:04

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);
查看更多
乱世女痞
3楼-- · 2020-06-25 05:09

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.

查看更多
登录 后发表回答