Remove key from hashmap when hashset is empty

I have a hashmap that matches strings with hash set values, and I want to remove the key from the hash map when the hashset hashmaps value is empty. I have problems with this. Here is what I tried, but I am very stuck:

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...
}
+5
source share
3 answers

To avoid ConcurrentModificationException, you need to use the interface directly 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();
    }
}

The reason your current code doesn't work is because you are trying to remove items from the map while iterating over it. When you call stringIDMap.remove(), it invalidates the iterator that is used for each loop under the cover, making further iteration impossible.

it.remove() , .

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

Starting with Java 8, there is a very short lambda solution:

stringIDMap.entrySet().removeIf(ent -> ent.getValue().isEmpty());
0
source

All Articles