Sunday, 27 January 2019

Groovy: Map: Group the elements


Using 'groupBy' method, you can group the elements of a collection using given criteria.

public Map groupBy(Object closures)
Return new map grouped by keys on each criterion

Group the list of elements
groupEvenodd = numbers.groupBy{it %2 == 0}

Above statement group even and odd numbers.

HelloWorld.groovy
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

groupEvenodd = numbers.groupBy{it %2 == 0}

println "$groupEvenodd"

Output
[true:[0, 2, 4, 6, 8], false:[1, 3, 5, 7, 9]]

Group map of employees
employeesByGender = employees.groupBy {it.value.gender}

Above statement groups all the employees by their gender.


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, 17, 'Gopika', 'F' as char)
Employee emp4 = new Employee(4, 35, 'Krishna', 'M' as char)

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

employeesByGender = employees.groupBy {it.value.gender}

println "$employeesByGender"

Output
[F:[1:<id : 1, age : 32, name : Susmitha, gender : F>, 3:<id : 3, age : 17, name : Gopika, gender : F>], M:[2:<id : 2, age : 29, name : Krishna, gender : M>, 4:<id : 4, age : 35, name : Krishna, gender : M>]]



Previous                                                 Next                                                 Home

No comments:

Post a Comment