1.

How Do You Remove A Mapping While Iterating Over Hashmap In Java?

Answer»

Even though HashMap provides remove() method to remove a KEY and a key/value pair, you cannot use them to remove a mapping while traversing an HashMap, instead, you NEED to use the Iterator's remove method to remove a mapping as shown in the FOLLOWING example:

Iterator ITR = map.entrySet().iterator();

while(itr.hasNext()){

Map.Entry current = itr.next();

if(current.getKey().equals("matching"){

itr.remove(); // this will remove the current entry.

}

}

You can see that we have USED Iterator.remove() method to remove the current entry while traversing the map.

Even though HashMap provides remove() method to remove a key and a key/value pair, you cannot use them to remove a mapping while traversing an HashMap, instead, you need to use the Iterator's remove method to remove a mapping as shown in the following example:

Iterator itr = map.entrySet().iterator();

while(itr.hasNext()){

Map.Entry current = itr.next();

if(current.getKey().equals("matching"){

itr.remove(); // this will remove the current entry.

}

}

You can see that we have used Iterator.remove() method to remove the current entry while traversing the map.



Discussion

No Comment Found