简体   繁体   English

findResults和Groovy中的collect有什么区别?

[英]what is the difference between findResults and collect in groovy?

Here is the code using collect 这是使用collect的代码

​def lst = [1,2,3,4];      
def newlst = [];       
newlst = lst.collect {element -> return element * element}       
println(newlst);

Here is the code using findResults 这是使用findResults的代码

def lst2 = [1,2,3,4];      
def newlst2 = [];       
newlst2 = lst2.findResults {element -> return element * element}       
println(newlst2);

​Both seem to return [1, 4, 9, 16] so what is the difference? 两者似乎都返回[1,4,9,16]有什么区别? Thanks! 谢谢!

Basically the difference is how they deal with null values 基本上区别在于它们如何处理null

collect when sees null will collect it, while findResults won't pick it. collect时看到null将收集它,而findResults不会选择它。

In other words, the size of resulting collection is the same as the size of input when using collect . 换句话说,结果集合的大小与使用collect时输入的大小相同。

Of course you could filter out the results but its an additional step 当然您可以过滤出结果,但这是一个额外的步骤

Here is a link to the example I've found in the internet 这是我在互联网上找到的示例的链接

Example: 例:

​def list = [1, 2, 3, 4]
println list.coll​​​​​​​​​​​​​​ect { it % 2 ? it : null}
// [1, null, 3, null] 
println list.findResults { it % 2 ? it : null}​
// [1,3]

When we need to check if returned list is empty then findResults seem more useful. 当我们需要检查返回的列表是否为空时,findResults似乎更有用。 Thanks to Mark for the answer. 感谢Mark的回答。

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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM