如何在迭代时从HashMap中删除密钥?
我有HashMap称为testMap其中包含String, String 。 
 HashMap<String, String> testMap = new HashMap<String, String>(); 
 迭代映射时,如果value与指定的string匹配,我需要从映射中删除键。 
即
 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)" 
	
尝试:
 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 -> !TestMap.contains("Sample")); 
使用Iterator.remove()。
从hashmap使用中删除特定的键和元素
 hashmap.remove(key) 
完整的源代码就像
 import java.util.HashMap; public class RemoveMapping { public static void main(String a[]){ HashMap hashMap = new HashMap(); hashMap.put(1, "One"); hashMap.put(2, "Two"); hashMap.put(3, "Three"); System.out.println("Original HashMap : "+hashMap); hashMap.remove(3); System.out.println("Changed HashMap : "+hashMap); } } 
来源: http : //www.tutorialdata.com/examples/java/collection-framework/hashmap/remove-mapping-of-specified–key-from-hashmap