Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy remove Collection item while iterating

Tags:

groovy

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()?

like image 277
Steve Kuo Avatar asked Jan 10 '12 18:01

Steve Kuo


People also ask

How do you remove an entry from a Collection while iterating over a Collection?

An element can be removed from a Collection using the Iterator method remove(). This method removes the current element in the Collection. If the remove() method is not preceded by the next() method, then the exception IllegalStateException is thrown.

How do you remove an element from a list while iterating?

If you want to delete elements from a list while iterating, use a while-loop so you can alter the current index and end index after each deletion.

Can we remove from list while iterating?

In Java 8, we can use the Collection#removeIf API to remove items from a List while iterating it.

Can we remove element from ArrayList while iterating?

ArrayList provides the remove() methods, like remove (int index) and remove (Object element), you cannot use them to remove items while iterating over ArrayList in Java because they will throw ConcurrentModificationException if called during iteration.


1 Answers

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.

like image 128
Dave Newton Avatar answered Sep 23 '22 05:09

Dave Newton