我HashMap打电话给testMapwhich contains String, String。
HashMap
testMap
String, String
HashMap<String, String> testMap = new HashMap<String, String>();
迭代地图时,如果value与指定的字符串匹配,我需要从地图中删除键。
value
IE
for(Map.Entry<String, String> entry : testMap.entrySet()) { if(entry.getValue().equalsIgnoreCase("Sample")) { testMap.remove(entry.getKey()); } }
testMap包含"Sample"但我无法从中删除密钥HashMap。 而是得到错误:
"Sample"
"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 及更高版本,您只需一行即可完成上述操作:
testMap.entrySet().removeIf(entry -> "Sample".equalsIgnoreCase(entry.getValue()));