Groovy迭代时删除集合项目 [英] Groovy remove Collection item while iterating
问题描述
在迭代时是否有Groovy方法去除集合的项目?在Java中,这是通过使用 Iterator.remove()
完成的:
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();
}
}
Groovy是否在其语言中提供了迭代式语法,还是我有使用 Iterator.remove()
?
Does Groovy provide remove-while-iterating in its language syntax, or do I have do use Iterator.remove()
?
推荐答案
Use removeAll()
.
> c = [1, 2, 3, 4, 5]
> c.removeAll { it % 2 == 0 }
> println c
[1, 3, 5]
您具体询问while iterating ,你是否试图用/每个对象做某件事? removeAll
仍然有效,只要封闭的最后一条语句仍然是truthy / falsey(和以前一样):
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]
闭包的返回值最后一条语句或明确的 return
值)是truthy / falsey,它将用于确定应该删除的内容。它不需要明确引用每个对象。
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.
这篇关于Groovy迭代时删除集合项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!