[java] How to remove a key from HashMap while iterating over it?

I am having HashMap called testMap which contains String, String.

HashMap<String, String> testMap = new HashMap<String, String>();

When iterating the map, if value is match with specified string, I need to remove the key from map.

i.e.

for(Map.Entry<String, String> entry : testMap.entrySet()) {
  if(entry.getValue().equalsIgnoreCase("Sample")) {
    testMap.remove(entry.getKey());
  }
}

testMap contains "Sample" but I am unable to remove the key from HashMap.
Instead getting error :

"Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.HashMap$HashIterator.nextEntry(Unknown Source)
    at java.util.HashMap$EntryIterator.next(Unknown Source)
    at java.util.HashMap$EntryIterator.next(Unknown Source)"

This question is related to java dictionary

The answer is


To remove specific key and element from hashmap use

hashmap.remove(key)

full source code is like

import java.util.HashMap;
public class RemoveMapping {
     public static void main(String a[]){
        HashMap hashMap = new HashMap();
        hashMap.put(1, "One");
        hashMap.put(2, "Two");
        hashMap.put(3, "Three");
        System.out.println("Original HashMap : "+hashMap);
        hashMap.remove(3);   
        System.out.println("Changed HashMap : "+hashMap);        
    }
}

Source : http://www.tutorialdata.com/examples/java/collection-framework/hashmap/remove-mapping-of-specified--key-from-hashmap