views:

53

answers:

3

I'm trying to remove objects from a list when it finds that particular objects privacy is private to the current user

     books.eachWithIndex{ obj, i ->

        if((obj.book.private).equals(true)){

          def status = bookService.getBookStatus(obj.book)

          if(!status){
               books.remove(i)
          }
        }
     }

error thrown as it tries to remove the object

ERROR errors.GrailsExceptionResolver - null java.util.ConcurrentModificationException

Q: is there any way to remove an object from a list within itself or would you have to separately store the index values and remove objects from outside the each loop?

+1  A: 

There is an iterator that has a .remove() method, but I don't know if that functionality has been translated into groovyesque. It doesn't work with Java's enhanced for either.

Try iterating over it manually (with an iterator, normal old-school Java-style for loop) and use the iterator.remove()... Unless Groovy has provided you with access to the iterator, it's the only way to do it while you are iterating.

Bill K
+5  A: 

A more functional approach may help:

def publicBooks = books.findAll { obj ->
    !obj.book.isPrivate() || bookService.getBookStatus(obj.book) 
} 

Note that findAll() returns a new collection rather than modifying the existing one.

Peter Niederwieser
A: 

The hibernate filters plugin was created for exactly this kind of scenario. I've used it on our current project to do this kind of filtering.

Ted Naleid