问题描述
我有一个将字符串键映射到哈希集值的哈希映射,我想在哈希映射的哈希集值为空时从哈希映射中删除一个键。我在解决这个问题时遇到了麻烦。这是我尝试过的,但我很困难:
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...
}
推荐答案
为了避免,您需要直接使用 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.
这篇关于当值的哈希集为空时,移除哈希映射中的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!