2014-01-07 48 views
12

我有一个集合,我想找到某些元素并对其进行转换。我可以在两次关闭中做到这一点,但我想知道只有一次可能吗?仅当结果不为空时收集

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

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

result = result.collect { 
    it /= 2 
} 

我的真实使用情况是摇篮,我想找到特定的文件一大堆,并将它们转化为自己的完全合格的包名。

回答

23

您可以使用findResults

c.findResults { i -> 
    i % 2 == 0 ? // if this is true 
     it/2 : // return this 
     null  // otherwise skip this one 
} 
+0

这是对我的鼻子在整个时间下...谢谢你。 (在问题足够大的时候将会接受答案) – Lerp

+0

嗯,这和我的OP不太一样吗? 'findResults'在第一个非空元素之后停止。 – Lerp

+0

你已经键入'findResult'而不是'findResults' ;-) –