迭代并从地图中删除 [英] 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 1.8开始,您可以使用:
As of Java 1.8 you could do this using with:
map.entrySet().removeIf(e-> <boolean expression> );
这篇关于迭代并从地图中删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文