如何在迭代时从HashMap中删除密钥?
2022-08-31 06:51:50
我正在调用哪个包含.HashMap
testMap
String, String
HashMap<String, String> testMap = new HashMap<String, String>();
迭代映射时,如果与指定的字符串匹配,我需要从映射中删除键。value
即
for(Map.Entry<String, String> entry : testMap.entrySet()) {
if(entry.getValue().equalsIgnoreCase("Sample")) {
testMap.remove(entry.getKey());
}
}
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)"