Grails/Groovy deleting an element in a collection while iterating over it

I ran into a recent problem whereby I wanted to delete a sub-set of the elements in a list after processing all elements in the list. The general gist of the logic was:


apples.each { apple ->
if(apple.red) apple.delete()
}


which resulted in a java.util.ConcurrentModificationException exception.

The solution is to remove the element from the interator before deleting it.


Iterator itr = apples.iterator()
while(itr.hasNext()){
def apple = itr.next()
itr.remove()
apple.delete()
}


For more a little more detail see this thread

Comments

Popular posts from this blog

AngularJs: User friendly date display with AngularJs and MomentJs

Getting started with Grails functional tests using Geb + Spock

Nerd Tree: A File Explorer with Mac Vim