Sunday 27 January 2019

Groovy: Map: collect(): Collect the information


public List collect(Closure transform)
Collect is used to transform the values

Below statement collect ages of all the employees
allAges = employees.collect{it.value.age}

Below statement collect names of all the employees
allNames = employees.collect{it.value.name}

Find the below working application.

HelloWorld.groovy

class Employee{
 String name
 int age
 int id
 char gender
 
 public Employee(int id, int age, String name, char gender){
  this.id = id
  this.age = age
  this.name = name
  this.gender = gender
 }
 
 String toString(){
  return "<id : ${this.id}, age : ${this.age}, name : ${this.name}, gender : ${this.gender}>"
 }
}

Employee emp1 = new Employee(1, 32, 'Susmitha', 'F' as char)
Employee emp2 = new Employee(2, 29, 'Krishna', 'M' as char)
Employee emp3 = new Employee(3, 41, 'Gopika', 'F' as char)
Employee emp4 = new Employee(4, 35, 'krishna', 'M' as char)

employees = [
 1 : emp1,
 2 : emp2,
 3 : emp3,
 4 : emp4
]

allAges = employees.collect{it.value.age}
allNames = employees.collect{it.value.name}

println "All employee ages : $allAges"
println "All employee names : $allNames"

Output
All employee ages : [32, 29, 41, 35]
All employee names : [Susmitha, Krishna, Gopika, krishna]



Previous                                                 Next                                                 Home

No comments:

Post a Comment