Using GroupBy method in groovy to aggregate the result in collection.

Given a collection of customer data we can group the result based on certain properties. Lets look into the example code for implementing GroupBy in groovy.

class Customer{
String id
String name
String city
String country
BigDecimal salary
String toString(){
    "$name"
}
}

def customer1 = new Customer(id:1,name:'krishna',city:'dhanbad',country:'India',salary:50000)
def customer2 = new Customer(id:2,name:'aman',city:'delhi',country:'India',salary:20000)
def customer3 = new Customer(id:3,name:'rahul',city:'oakland',country:'USA',salary:30000)
def customer4 = new Customer(id:4,name:'rina',city:'oxford',country:'USA',salary:40000)
def customer5 = new Customer(id:5,name:'rozario',city:'moscow',country:'RUSSIA',salary:4500)
def customer6 = new Customer(id:6,name:'rozario',city:'moscow',country:'RUSSIA',salary:14500)
def customers= [customer1,customer2,customer3,customer4,customer5,customer6]
def result = customers.groupBy({ customer -> customer.country })
println result // [India:[krishna, aman], USA:[rahul, rina], RUSSIA:[rozario, rozario]]

result.each{key,val->
println "country is $key with customer names = $val"
}
//country is India with customer names = [krishna, aman]
//country is USA with customer names = [rahul, rina]
//country is RUSSIA with customer names = [rozario, rozario]


def result1 = customers.groupBy({ customer -> customer.name }).collect{k,v->[(k):v.salary.sum()]}
println result1 //[[krishna:50000], [aman:20000], [rahul:30000], [rina:40000], [rozario:19000]]

In the above example code groupBy is first applied to country property of customer class which returns a map with property as key and object as values.

In the next example groupBy is applied to cutomer name property and then a collect method is applied over it to return a custom map with property as key and sum as value. Sum is like an aggregate function applied on a list of salary.

groupBy and collect method accepts a closure as an argument.