加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Groovy在迭代时删除Collection项

发布时间:2020-12-14 16:34:44 所属栏目:大数据 来源:网络整理
导读:有没有Groovy的方式来删除集合的项目,而迭代?在 Java中,这是使用Iterator.remove()完成的: Collection collection = ...for (Iterator it=collection.iterator(); it.hasNext(); ) { Object obj = it.next(); if (should remove) { it.remove(); }} Groovy
有没有Groovy的方式来删除集合的项目,而迭代?在 Java中,这是使用Iterator.remove()完成的:

Collection collection = ...
for (Iterator it=collection.iterator(); it.hasNext(); ) {
    Object obj = it.next();
    if (should remove) {
        it.remove();
    }
}

Groovy是否在其语言语法中提供删除同时迭代,还是使用Iterator.remove()?

解决方法

Use removeAll().

> c = [1,2,3,4,5]
> c.removeAll { it % 2 == 0 }
> println c
[1,5]

您具体询问“迭代”时,是否尝试与每个对象进行某些操作? removeAll仍然可以工作,只要关闭的最后一个语句仍然是真实/ falsey(如前所述):

> 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,3]

闭包的返回值(最后一个语句的值或显式返回值)是真实的/假的,它将用于确定应该删除的内容.它不需要明确地引用每个对象.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读