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

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

问题描述

我有一个名为 testMapHashMap,其中包含 String, String.

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

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

迭代地图时,如果value与指定的字符串匹配,我需要从地图中删除键.

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

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

使用 Java 1.8 及更高版本,您只需一行即可完成上述操作:

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

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

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

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