user840718 user840718 - 17 days ago 5
Java Question

Remove duplicates from ArrayList issue

I'm trying to remove duplicates from ArrayLists with the popular technique:

yourList = new ArrayList<String>(new LinkedHashSet<String>(yourList));


It works, but since the ArrayList is in an HashMap I got the problem.

private void removeDuplicate(HashMap<String, ArrayList<LinkedList<String>>> p)
{
//cycle for each entry of HashMap
for(Map.Entry<String, ArrayList<LinkedList<String>>> entry : p.entrySet())
{
ArrayList<LinkedList<String>> partitions = entry.getValue();
partitions = new ArrayList<LinkedList<String>>(new LinkedHashSet<LinkedList<String>>(partitions));

}
}


The problem is after that, the HashMap is exactly the same like before!
The variable partitions has no duplicates anymore, but the entire HashMap is unchanged.
Where is the problem?

Answer

You only modify partitions which is only a local variable, you don't actually modify the value of the map entry, to update the value of a given map entry use Map.Entry#setValue(V value)

for(Map.Entry<String, ArrayList<LinkedList<String>>> entry : p.entrySet()) {
    ArrayList<LinkedList<String>> partitions = entry.getValue();
    entry.setValue(new ArrayList<>(new LinkedHashSet<>(partitions)));
}

NB: This will remove LinkedList duplicates not String duplicates

Comments