Search code examples
javahashmapconcurrentmodification

Delete elements from Hashmap while iterating over it


Here is my code. I have an arraylist of visited elements. So I want delete these visited elements from the hashmap and below is code. It gives me concurrentmodification exception.

private static void removeVisitedNodes(ArrayList<String> arrayList) {
    // TODO Auto-generated method stub

    Iterator<String> it = arrayList.iterator();
    String temp;
    while(it.hasNext())
    {
        temp = it.next();
        System.out.println("temp is " + temp);
        Iterator<Entry<String, ArrayList<String>>> iter = neighbours_reachability_map.entrySet().iterator();

        // iterate through the hashmap to remove elements
        while (iter.hasNext()) {
            Entry<String, ArrayList<String>> entry = iter.next();
            if(entry.getValue().contains(temp)){
                //System.out.println("Contains it"  + entry.getValue().toString());
                entry.getValue().remove(temp);
            }
        }

    }
}

I checked up a few other similar questions but they did not help much. Is there a neater way to do this without causing an exception? Thanks in advance for your help.


Solution

  • To remove a element whilst in the middle of iterating, use Iterator.remove().