开发者

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

开发者 https://www.devze.com 2023-03-07 12:36 出处:网络
This question already has an开发者_开发百科swers here: iterating over and removing from a map [duplicate]
This question already has an开发者_开发百科swers here: iterating over and removing from a map [duplicate] (12 answers) Closed 9 years ago.

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


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()));


Use Iterator.remove().

0

精彩评论

暂无评论...
验证码 换一张
取 消