当值的hashset为Empty时,删除hashmap中的键

我有一个将字符串键映射到hashsets值的hashmap,我想在hashmaps的hashset值为空时从hashmap中删除一个键。 我无法接近这个。 这是我尝试过的但是我很困惑:

for(Map.Entry<String, HashSet> entr : stringIDMap.entrySet()) { String key = entr.getKey(); if (stringIDMap.get(key).isEmpty()) { stringIDMap.remove(key); continue; } //few print statements... } 

为了避免ConcurrentModificationException ,您需要直接使用Iterator接口:

 Iterator>> it = stringIDMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry> e = it.next(); String key = e.getKey(); HashSet value = e.getValue(); if (value.isEmpty()) { it.remove(); } } 

您当前代码不起作用的原因是您尝试在迭代时从地图中删除元素。 当你调用stringIDMap.remove() ,这会使for-each循环在封面下使用的迭代器失效,从而无法进行进一步的迭代。

it.remove()解决了这个问题,因为它不会使迭代器失效。

  Iterator iterator = mMapFiles.keySet().iterator(); while (iterator.hasNext()){ if ( mMapFiles.get( iterator.next() ).size() < 1 ) iterator.remove(); }