迭代并从地图中删除 [英] iterating over and removing from a map
本文介绍了迭代并从地图中删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在做:
for (Object key : map.keySet())
if (something)
map.remove(key);
抛出了 ConcurrentModificationException,所以我将其更改为:
which threw a ConcurrentModificationException, so i changed it to:
for (Object key : new ArrayList<Object>(map.keySet()))
if (something)
map.remove(key);
这个和任何其他修改映射的过程都在同步块中.
this, and any other procedures that modify the map are in synchronized blocks.
有更好的解决方案吗?
推荐答案
从 Java 8 开始,您可以按如下方式执行此操作:
As of Java 8 you could do this as follows:
map.entrySet().removeIf(e -> <boolean expression>);
Oracle 文档:entrySet()
Oracle Docs: entrySet()
集合由地图支持,因此对地图的更改会反映在集合中,反之亦然
The set is backed by the map, so changes to the map are reflected in the set, and vice-versa
这篇关于迭代并从地图中删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文