Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the difference between findResults and collect in groovy?

Tags:

groovy

Here is the code using collect

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

Here is the code using 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? Thanks!

like image 455
kofhearts Avatar asked Oct 18 '25 13:10

kofhearts


1 Answers

Basically the difference is how they deal with null values

collect when sees null will collect it, while findResults won't pick it.

In other words, the size of resulting collection is the same as the size of input when using 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]
like image 165
Mark Bramnik Avatar answered Oct 22 '25 05:10

Mark Bramnik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!