Tuesday, 22 January 2019

Groovy: collect() : Transform the elements of list to new list


By using collect() method, we can create new list by transforming the existing elements of the list.

HelloWorld.groovy
evenNumbers = [0, 2, 4, 6, 8]

squaresOfEvenNumbers = evenNumbers.collect {it * 2}

println "evenNumbers : $evenNumbers"
println "squaresOfEvenNumbers : $squaresOfEvenNumbers"

Output
evenNumbers : [0, 2, 4, 6, 8]
squaresOfEvenNumbers : [0, 4, 8, 12, 16]

You can even achieve the same result on a list using *. Operator.


HelloWorld.groovy
evenNumbers = [0, 2, 4, 6, 8]

squaresOfEvenNumbers = evenNumbers*.multiply(2)
sumEveryNumBy2 = evenNumbers*.plus(2)

println "evenNumbers : $evenNumbers"
println "squaresOfEvenNumbers : $squaresOfEvenNumbers"
println "sumEveryNumBy2 : $sumEveryNumBy2"

Output
evenNumbers : [0, 2, 4, 6, 8]
squaresOfEvenNumbers : [0, 4, 8, 12, 16]
sumEveryNumBy2 : [2, 4, 6, 8, 10]

You can even pass a list as argument to collect method to collect the final results.


HelloWorld.groovy
evenNumbers = [0, 2, 4, 6, 8]
squaresOfEvenNumbers = []

evenNumbers.collect(squaresOfEvenNumbers) {it * it}

println "evenNumbers : $evenNumbers"
println "squaresOfEvenNumbers : $squaresOfEvenNumbers"

Output
evenNumbers : [0, 2, 4, 6, 8]
squaresOfEvenNumbers : [0, 4, 16, 36, 64]





Previous                                                 Next                                                 Home

No comments:

Post a Comment