Monday 14 January 2019

Groovy: Spread Operator (*.)


Spread (*.) operator is used to invoke an action on all items of an aggregate object.

def employees = [
         new Employee (firstName : "Menon", lastName : "Hari"),
         new Employee (firstName : "Bhat", lastName : "Srini"),
         new Employee (firstName : "Krishna", lastName : "Gurram")
]

Below statement return all the first names of the employees.
def firsNames = employees*.firstName

Below statement return all the last names of the employees.
def lastNames = employees*.lastName

Find the below working application.

HelloWorld.groovy
class Employee{
 String firstName
 String lastName
}

def employees = [
 new Employee (firstName : "Menon", lastName : "Hari"),
 new Employee (firstName : "Bhat", lastName : "Srini"),
 new Employee (firstName : "Krishna", lastName : "Gurram")
]

def firsNames = employees*.firstName
def lastNames = employees*.lastName

println "firstNames : ${firsNames}"
println "lastNames : ${lastNames}"


Output
firstNames : [Menon, Bhat, Krishna]
lastNames : [Hari, Srini, Gurram]

Is spread operator null safe?
Yes, spread operator is null safe, if any element in the collection is null, then it returns null instead of throwing NullPointerException.


HelloWorld.groovy
class Employee{
 String firstName
 String lastName
}

def employees = [
 null,
 new Employee (firstName : "Menon", lastName : "Hari"),
 null,
 new Employee (firstName : "Bhat", lastName : "Srini"),
 null,
 new Employee (firstName : "Krishna", lastName : "Gurram"),
 null
]

def firsNames = employees*.firstName
def lastNames = employees*.lastName

println "firstNames : ${firsNames}"
println "lastNames : ${lastNames}"


Output
firstNames : [null, Menon, null, Bhat, null, Krishna, null]
lastNames : [null, Hari, null, Srini, null, Gurram, null]

You can even perform operation 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]



Previous                                                 Next                                                 Home

No comments:

Post a Comment