在删除和更新集合时通过哈希图迭代
我有一个计数图,可以在其中跟踪字符串中字符的数量。我想迭代该地图,减少当前访问的角色计数,并在达到零时将其删除。
如何在Java完成?
HashMap<Character, Integer> characterCount = new HashMap<>();
characterCount.put('a', 2);
characterCount.put('b', 1);
characterCount.put('c', 1);
Iterator<Map.Entry<Character, Integer>> iterator = characterCount.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Character, Integer> entry = iterator.next();
// Decrement the chosen character from the map
if (entry.getValue() == 1) {
iterator.remove();
} else {
characterCount.put(entry.getKey(), entry.getValue() - 1);
}
// Call some logic the relies on the map with the remaining character count.
// I want the characterCount.size() to return zero when there is no character with count > 0
doSomeLogic(characterCount);
// Restore the character to the map
characterCount.put(entry.getKey(), entry.getValue());
}
以上代码导致consurrentModificationException
。
I have a count map where I keep track of the numbers of characters from a string. I want to iterate over that map, decrement the currently visited character count AND remove it if it reaches zero.
How can that be done in Java?
HashMap<Character, Integer> characterCount = new HashMap<>();
characterCount.put('a', 2);
characterCount.put('b', 1);
characterCount.put('c', 1);
Iterator<Map.Entry<Character, Integer>> iterator = characterCount.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Character, Integer> entry = iterator.next();
// Decrement the chosen character from the map
if (entry.getValue() == 1) {
iterator.remove();
} else {
characterCount.put(entry.getKey(), entry.getValue() - 1);
}
// Call some logic the relies on the map with the remaining character count.
// I want the characterCount.size() to return zero when there is no character with count > 0
doSomeLogic(characterCount);
// Restore the character to the map
characterCount.put(entry.getKey(), entry.getValue());
}
The above code results in a ConcurrentModificationException
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于
MAP#entrySet
返回地图中映射的视图,因此直接设置entry
的值以更新它。Since
Map#entrySet
returns a view of the mappings in the map, directly set the value of theEntry
to update it.这是一种方法。
map.computeifpresent
将在null
时删除条目。如果目前是1
(即将降低),则使用三元运算符降低值或替换为null
。打印
因此,这是它对您有效的方式,更换迭代器和循环时。
Here is one way.
Map.computeIfPresent
will remove the entry when it becomesnull
. Using the ternary operator either decrements the value or replaces withnull
if it is presently1
(about to be decremented).prints
So, here is how it would work for you, replacing your iterator and while loop.