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

JavaDictionary

Java Problem Overview


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)"

Java Solutions


Solution 1 - Java

Try:

Iterator<Map.Entry<String,String>> iter = testMap.entrySet().iterator();
while (iter.hasNext()) {
    Map.Entry<String,String> entry = iter.next();
    if("Sample".equalsIgnoreCase(entry.getValue())){
        iter.remove();
    }
}

With Java 1.8 and onwards you can do the above in just one line:

testMap.entrySet().removeIf(entry -> "Sample".equalsIgnoreCase(entry.getValue()));

Solution 2 - Java

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionssbecseView Question on Stackoverflow
Solution 1 - JavaTomView Answer on Stackoverflow
Solution 2 - JavaPrince John WesleyView Answer on Stackoverflow