从HashMap中移除项目,Java问题?

Mav*_*vin 3 java collections

您好我想通过应用标准从HashMap中删除项目.考虑以下代码:

Set<Foo> set = myMap.keySet();
Iterator<Foo> itr = set.iterator();
while (itr.hasNext())
{
    Foo foo = itr.next();
    if (foo.toString().length() < 3) {
        myMap.remove(foo); //remove the pair if key length is less than 3
    }
}
Run Code Online (Sandbox Code Playgroud)

所以我得到运行时ConcurentModification Exception,因为在迭代期间我正在修改HashMap.我该怎么办?有没有其他方法来搜索我的crieteria并在最后执行remove命令,以便我可以避免这个异常?

a_h*_*ame 13

itr.remove()而不是myMap.remove(o.toString())