2013-04-08 38 views
4

我有一个将字符串键映射到哈希集值的哈希映射,并且当hashmaps的哈希集值为空时,我想从哈希映射中移除一个键。我在解决这个问题时遇到了麻烦。这是我做过尝试,但我很卡:当值的哈希集为空时,移除哈希映射中的键

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... 
} 
+0

对于某些字符串,hashmap中的值即HashSet 是否为null?你现在面临的问题是什么?获得NullPointer? – JRR 2013-04-08 06:11:31

回答

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(); 
    } 
} 

当前的代码不在理由工作是你试图从地图上移除元素,同时迭代它。当你调用​​时,这会使for-each循环在封面下使用的迭代器失效,从而无法进一步迭代。

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

+2

这可能是他卡在... – Thihara 2013-04-08 06:10:38

+0

正是我得到的错误。谢谢 – Sempiternal 2013-04-08 06:14:17

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