这是使用收集的代码
def lst = [1,2,3,4];
def newlst = [];
newlst = lst.collect {element -> return element * element}
println(newlst);
这是使用 findResults 的代码
def lst2 = [1,2,3,4];
def newlst2 = [];
newlst2 = lst2.findResults {element -> return element * element}
println(newlst2);
两者似乎都返回 [1, 4, 9, 16] 那么有什么区别呢?谢谢!
基本上区别在于它们如何处理null
值
collect
看到null
会收集它,而findResults
不会选择它。
换句话说,结果集合的大小与使用 collect
时输入的大小相同。
当然,您可以过滤掉结果,但这是一个额外的步骤
这是我在互联网上找到的示例的链接
例:
def list = [1, 2, 3, 4]
println list.collect { it % 2 ? it : null}
// [1, null, 3, null]
println list.findResults { it % 2 ? it : null}
// [1,3]
当我们需要检查返回的列表是否为空时,findResults似乎更有用。感谢马克的回答。
def list = [1, 2, 3, 4]
def l1 = list.collect { it % 100 == 0 ? it : null}
def l2 = list.findResults { it % 100 == 0 ? it : null}
if(l1){
println("not null/empty " + l1)
}
if(l2){
println("not null/empty " + l2)
}