Sem*_*nal 6 java hashmap set hashset
我有一个将字符串键映射到hashsets值的hashmap,我想在hashmaps的hashset值为空时从hashmap中删除一个键.我无法接近这个.这是我尝试过但我很困惑的事情:
for(Map.Entry<String, HashSet<Integer>> entr : stringIDMap.entrySet())
{
String key = entr.getKey();
if (stringIDMap.get(key).isEmpty())
{
stringIDMap.remove(key);
continue;
}
//few print statements...
}
Run Code Online (Sandbox Code Playgroud)
NPE*_*NPE 17
为了避免ConcurrentModificationException,您需要Iterator直接使用该界面:
Iterator<Map.Entry<String, HashSet<Integer>>> it = stringIDMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, HashSet<Integer>> e = it.next();
String key = e.getKey();
HashSet<Integer> value = e.getValue();
if (value.isEmpty()) {
it.remove();
}
}
Run Code Online (Sandbox Code Playgroud)
您当前代码不起作用的原因是您尝试在迭代时从地图中删除元素.当你调用时stringIDMap.remove(),这会使for-each循环在封面下使用的迭代器失效,从而无法进行进一步的迭代.
it.remove() 解决了这个问题,因为它不会使迭代器失效.