Remove a key in hashmap when the value's hashset is Empty

风流意气都作罢 提交于 2019-12-05 07:28:25

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.

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

Since Java 8, there is an excelent short solution with lambda:

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

or you can use more concise way by passing method reference

stringIDMap.values().removeIf(Set::isEmpty);

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!