Sort Objects Using Groovy

Posted on Feb - 2017

by krishna singh

Making object sorting simpler using groovy

Groovy brings out a very simple way of sorting objects using a special operator named as spaceship operator <=>

Ex:

class Person{

String name
Integer age
Long salary

public String toString(){
  "${name} : ${age} : ${salary}"
}

}
def list = [] // groovy inbuilt support for declaring array list
def ins1 = new Person([name:'xyz',age:21,salary:24555]) // groovy way of creating objects using map as constructor
def ins2 = new Person([name:'abc',age:51,salary:4555])
def ins3 = new Person([name:'lmn',age:27,salary:44212])
def ins4 = new Person([name:'pos',age:13,salary:21556])
def ins5 = new Person([name:'ghj',age:33,salary:32522])
list.addAll([ins1,ins2,ins3,ins4,ins5])

def sortByName = {ob1,ob2->ob1.name <=> ob2.name}
def sortByAge = {ob1,ob2->ob1.age <=> ob2.age}

def sortBySalary = {ob1,ob2->ob1.salary <=> ob2.salary}

list.sort(sortBySalary) // pass any defined closure as an argument for sorting

How does spaceship operator works:

Spaceship operator return three integer value 1, -1 , 0 based on the comparison shown in example below:

println 'b'<=>'a' // return 1 if left argument is greater than right
println 'a'<=>'b' // return -1 if left argument is less than right
println 'a'<=>'a' // return 0 if left argument is equal to right

Happy coding with groovy smiley.