问题
这个问题在这里已有答案:
- 迭代并从 Map 中删除[重复] 12个答案
我有HashMap
被叫testMap
,其中包含String, String
。
HashMap<String, String> testMap = new HashMap<String, String>();
迭代 Map 时,ifvalue
与指定的字符串匹配,我需要从 Map 中删除该键。
即
for(Map.Entry<String, String> entry : testMap.entrySet()) {
if(entry.getValue().equalsIgnoreCase("Sample")) {
testMap.remove(entry.getKey());
}
}
testMap
contains"Sample"
但我无法从5334139978删除密钥。
而是得到错误:
"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)"
#1 热门回答(265 赞)
尝试:
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"));
#2 热门回答(15 赞)
#3 热门回答(-33 赞)
从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);
}
}