I have a hashmap that maps strings keys to hashsets values, and I want to remove a key from the hashmap when the hashmaps's hashset value is empty. I'm having trouble approaching this. Here's what I've tried but I'm 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...
}
In order to avoid ConcurrentModificationException
, you need to use the Iterator
interface directly:
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 that you are attempting to remove elements from the map while iterating over it. When you call stringIDMap.remove()
, this invalidates the iterator that the for-each loop uses under the cover, making further iteration impossible.
it.remove()
solves this problem as it does not invalidate the iterator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With