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]
When we need to check if returned list is empty then findResults seem more useful. Thanks to Mark for the answer.
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)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.