Monday 14 January 2019

Groovy: Spread operator and nested objects


Spread operator can be applied on nested object.

For example, below statement return hobbies of all the employees.
hobbyNames = employees*.hobbies*.hobbyName

Find the below working application.

HelloWorld.groovy
class Employee{
 String firstName
 String lastName
 List<Hobby> hobbies
}

class Hobby{
 String hobbyName
 
 public Hobby(String hobbyName){
  this.hobbyName = hobbyName
 }
}

def employees = [
 new Employee (firstName : "Menon", lastName : "Hari", hobbies : [new Hobby("Cricket"), new Hobby("football")]),
 new Employee (firstName : "Bhat", lastName : "Srini",  hobbies : [new Hobby("Cycling"), new Hobby("Golf")]),
 new Employee (firstName : "Krishna", lastName : "Gurram",  hobbies : [new Hobby("Polo"), new Hobby("Hockey")])
]

hobbyNames = employees*.hobbies*.hobbyName
println "Hobby Names : ${hobbyNames}" 

Output
Hobby Names : [[Cricket, football], [Cycling, Golf], [Polo, Hockey]]


Previous                                                 Next                                                 Home

No comments:

Post a Comment