当值的哈希集为空时,移除哈希映射中的键 [英] Remove a key in hashmap when the value's hashset is Empty

查看:91
本文介绍了当值的哈希集为空时,移除哈希映射中的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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


推荐答案

为了避免 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();
    }
}

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

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()解决了这个问题,因为它不会使迭代器失效。

it.remove() solves this problem as it does not invalidate the iterator.

这篇关于当值的哈希集为空时,移除哈希映射中的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆