Hello Guys,

Recently working on one of my projects where I have to sort an employee data by multiple parameters, I spend multiple hours for this and came across to this solution.

The spaceship operator has it’s roots in Perl and has found it’s way in to languages like Groovy and Ruby. The spaceship is a relational operator that performs like Java’s compareTo() comparing two objects and returning -1, 0, or +1 depending on the value of the left argument as compared to the right. If the left argument is greater than the right, the operator returns 1. If the left argument is less than the right, the operator returns −1. If the arguments are equal, 0 is returned. When using Groovy/Grails, if the arguments are not of comparable types, a ClassCastException is thrown.

Here is a list which is being sorted by spaceship operator.

 

Syntax:

employeeList.sort { first,second ->
first.firstName <=> second.firstName ?: first.lastName <=> second.lastName ?: first.age <=> second.age
}

Output:

 

Spaceship operator is very useful in sorting, The greatest advantage of using the Groovy comparison operators is the graceful handling of nulls such that x <=> y will never throw a NullPointerException.

 
String name = “rahul”;
println name <=> null

String name = “rahul”;
println null <=> name

String name = “rahul”;
println null <=> null

Output :

1

-1

0

I hope you like this !. If you have any question please comment.