Tuesday, May 25, 2010

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()
def apple = itr.next()

For more a little more detail see this thread

No comments:

Post a Comment