I want to remove an item from HashMap, by applying a criteria. Consider this code:
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
}
}
So I get a ConcurentModificationException because during the iteration I am modifying the HashMap. What should I do? Is there any other way to search for my criteria and execute the remove command at the end so that I can avoid this exception?
Use
itr.remove()instead ofmyMap.remove(o.toString())