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!
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.collect { it % 2 ? it : null}
// [1, null, 3, null]
println list.findResults { it % 2 ? it : null}
// [1,3]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With