AFAIK, there are two approaches:
- Iterate over a copy of the collection
- Use the iterator of the actual collection
For instance,
List<Foo> fooListCopy = new ArrayList<Foo>(fooList);
for(Foo foo : fooListCopy){
// modify actual fooList
}
and
Iterator<Foo> itr = fooList.iterator();
while(itr.hasNext()){
// modify actual fooList using itr.remove()
}
Are there any reasons to prefer one approach over the other (e.g. preferring the first approach for the simple reason of readability)?
In Java 8, there is another approach. Collection#removeIf
eg:
why not this?
And if it's a map, not a list, you can use keyset()