1

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?

1
  • how about you match the partitions with the Hashmap? Commented Nov 15, 2016 at 12:36

2 Answers 2

3

You're never writing the new list back into the map.

You just assign the original list of lists into partitions then assign a new value into it, and then don't use that new value in any way.

partitions = entry.getValue() is a reference assignment - it copies the reference to the original list into partitions variable. A new assignment into partitions overwrites the reference, not the object it refers to.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.