仅在结果不为null时收集

Ler*_*erp 18 groovy find collect gradle

我有一个集合,我想找到某些元素并对其进行转换.我可以在两个闭包中做到这一点,但我想知道是否有可能只有一个?

def c = [1, 2, 3, 4]

def result = c.findAll {
    it % 2 == 0
}

result = result.collect {
   it /= 2
}
Run Code Online (Sandbox Code Playgroud)

我的真实用例是使用Gradle,我想找到一组特定的文件并将它们转换为完全限定的包名.

tim*_*tes 34

你可以使用findResults:

c.findResults { i ->
    i % 2 == 0 ?    // if this is true
        it / 2 :    // return this
        null        // otherwise skip this one
}
Run Code Online (Sandbox Code Playgroud)

  • 是的,在文档中很难找到一些东西...... List,Iterable,Collection或Object都是候选页面的次数;-) (2认同)