When we interact with database records, we specify a criteria with an order(asc or desc) to get the results sorted by a particular field. Usually we sort on the basis of one field but a situation may arise to sort the objects on the basis of two or more fields. Here is a simple example:


Jellyfish a = new Jellyfish(age: 2, weight:5)

Jellyfish b = new Jellyfish(age: 5, weight:8)

Jellyfish c = new Jellyfish(age: 4, weight:7)

In the above code we have created few objects containing 2 fields


def objectList = [a,b,c]


objectList.sort{x,y -> x.age<=>y.age ?: x.weight<=>y.weight}

 

In the above code the sorting is done on the basis of age first, if 'age' of objects are same then sorting is done by 'weight' field.

We can use nested if/else statement to do sorting on the basis of more than 2 fields.

That was all 🙂