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.
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
onLinkedList
and write toTreeSet
. See code below:One way to do it is by using an auxiliary map:
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 theallPoints
list.