Use Iterator
.
Iterator<Map.Entry<String, Integer>> iter = this.toBuyItemEnumeration;
while (iter.hasNext()) {
Map.Entry<String, Integer> entry = iter.next();
if (some-condition){
iter.remove();
}
}
HOW IT WORKS ?
The javadoc for ConcurrentModificationException
says:
If a single thread issues a sequence of method invocations that violates the contract of an object, the object may throw this exception. For example, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception.
The field int expectedModCount
is initiated to be equal to the field protected transient int modCount = 0;
(and this is valid for Collections and Maps), and modCount
keeps track of the structural modifications over the object. If modCount
at some point of the iteration gets unequal to expectedModCount
, then a ConcurrentModificationException
is thrown.
With using Iterator
to make structural changes over the map/collection (like removing elements), we make sure that the removal operation will be executed properly, e.g. the modCount
will be equal to the expectedModCount
.