Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 583
maddie Avatar asked Jun 23 '26 03:06

maddie


2 Answers

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

like image 120
randers Avatar answered Jun 26 '26 19:06

randers


you can put the elementos you want to delete in another collection object and then, after finished the iteration, delete those elements

like image 44
Tupac Avatar answered Jun 26 '26 18:06

Tupac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!