在迭代时是否有一种Groovy方法来删除Collection的项目?在Java中,这是使用来完成Iterator.remove():
Collection collection = ...
for (Iterator it=collection.iterator(); it.hasNext(); ) {
Object obj = it.next();
if (should remove) {
it.remove();
}
}
Run Code Online (Sandbox Code Playgroud)
Groovy是否在其语言语法中提供了迭代删除,或者我是否使用过Iterator.remove()?
Dav*_*ton 27
> c = [1, 2, 3, 4, 5]
> c.removeAll { it % 2 == 0 }
> println c
[1, 3, 5]
Run Code Online (Sandbox Code Playgroud)
你特别询问"迭代时",你是否试图用/每个对象做一些事情?removeAll只要闭包的最后一个陈述仍然是真实的(如前所述),它仍然有效:
> 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]
Run Code Online (Sandbox Code Playgroud)
闭包的返回值(最后一个语句的return值或显式值)是真/假,它将用于确定应删除的内容.它不需要明确引用每个对象.