Steve Kuo
Steve Kuo

Reputation: 63084

Groovy remove Collection item while iterating

Is there a Groovy way of removing a Collection's item while iterating? In Java this is accomplished using Iterator.remove():

Collection collection = ...
for (Iterator it=collection.iterator(); it.hasNext(); ) {
    Object obj = it.next();
    if (should remove) {
        it.remove();
    }
}

Does Groovy provide remove-while-iterating in its language syntax, or do I have do use Iterator.remove()?

Upvotes: 16

Views: 17585

Answers (1)

Dave Newton
Dave Newton

Reputation: 160191

Use removeAll().

> c = [1, 2, 3, 4, 5]
> c.removeAll { it % 2 == 0 }
> println c
[1, 3, 5]

You ask specifically about "while iterating", are you trying to do something with/too each object? removeAll still works as long as the closure's last statement is still truthy/falsey (as before):

> c.removeAll { 
*     tmp = it * 10
*     println "ohai ${it}*10=${tmp}"
*     tmp >= 40
* }
ohai 1*10=10
ohai 2*20=20
ohai 3*30=30
ohai 4*40=40
ohai 5*50=50
> println c
[1, 2, 3]

The closure's return value (value of the last statement, or an explicit return value) is truthy/falsey, it will be used to determine what should be removed. It doesn't need to refer explicitly to each object.

Upvotes: 30

Related Questions