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()
?
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.
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.
In Java 8, we can use the Collection#removeIf API to remove items from a List while iterating it.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With