[B][Josh]: I like each better than Java 5's for-each statement because with Java you can't always use the for-each. For example, you can't do this in Java:
Why not? You'll get a ConcurrentModificationException (assuming you have something in myList that starts with "foo") because you can't remove an object from a List while you're iterating over it. You'd have to use the old for loop with an Iterator and call the Iterator's remove method. In Groovy, I can always use each for iteration, and I like that a lot.[/B]
But if you call myList.remove() inside a closure for myList.each(), you will likely get a ConcurrentModificationException too. At least, you will if myList is an ArrayList or LinkedList. Because under the covers, each() is using the iterator too.
Calling myList.remove() is a bad idea here anyway, very inefficient. It's unfortunate that Java (and thus Groovy) throws a ConcurrentModificationException even when there is clearly only one
thread involved - that's misleading. But while it shouldn't lead to incorrect results, using the list's remove() is pretty slow compared to using the remove() on the iterator. Especially if more than one item will be removed. So I don't see how Groovy's each() method helps here. It's just another way to iterate, unrelated to the real problem.
A nice alternative would be to simply use findAll() to create a new list without the items you don't like. For example:
I don't see a method that will delete entries from myList directly - instead we create a new list (and optionally replace the old with the new). Often that's preferable anyway. Of course you can just use the Iterator as you would in Java. For comparison, Ruby has a delete_if method that would operate directly on the current list: