相关疑难解决方法(0)

如何在迭代时从HashMap中删除一个键?

我正在HashMap调用testMap哪个包含String, String.

HashMap<String, String> testMap = new HashMap<String, String>();
Run Code Online (Sandbox Code Playgroud)

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

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

testMap包含"Sample"但我无法从中删除密钥HashMap.
而是得到错误:

"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)"
Run Code Online (Sandbox Code Playgroud)

java dictionary

149
推荐指数
2
解决办法
14万
查看次数

标签 统计

dictionary ×1

java ×1