Groovy在迭代时删除Collection项

Ste*_*Kuo 13 groovy

在迭代时是否有一种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

使用removeAll().

> 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值或显式值)是真/假,它将用于确定应删除的内容.它不需要明确引用每个对象.

  • @JarredOlson 如果您是 Groovy 的新手,我建议您避免手动执行基于迭代器的循环(或 `for (<three statements here>)` for 循环)。使用基于闭包的方法,如 `each`、`collect`、`findAll` 等,我从来不需要在 Groovy 中使用显式迭代器,这让我大为解脱 =D (2认同)