如何在迭代过程中从HashMap中删除一个密钥? [英] How to remove a key from HashMap while iterating over it?

查看:133
本文介绍了如何在迭代过程中从HashMap中删除一个密钥?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 HashMap 调用 testMap ,其中包含 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.

ie

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

testMap 包含Sample,但是我无法从 HashMap 中删除​​该键。
而不是出现错误:

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


推荐答案

尝试:

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

这篇关于如何在迭代过程中从HashMap中删除一个密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆