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()?
Use
removeAll().You ask specifically about “while iterating”, are you trying to do something with/too each object?
removeAllstill works as long as the closure’s last statement is still truthy/falsey (as before):The closure’s return value (value of the last statement, or an explicit
returnvalue) is truthy/falsey, it will be used to determine what should be removed. It doesn’t need to refer explicitly to each object.