Groovy's spaceship operator (<=>) delegates to the compareTo() method.
Examples
src/SpaceshipExample.groovy
def x = 1 <=> 2; // calls Integer.compareTo
println x
x = 1 <=> 1; // calls Integer.compareTo
println x
x = "b" <=> "a" // calls String.compareTo
println x
Output
-1 0 1
Following example shows the use of spaceship operator in Comparator.compare() method:
src/SpaceshipExample2.groovy
def strings = ["banana", "fig", "apple", "orange", "pie"];
def comparator = new Comparator<String>() {
@Override
int compare(String o1, String o2) {
return o1.length() != o2.length() ? o1.length() <=> o2.length() : o1 <=> o2;
}
}
Collections.sort(strings, comparator);
for (def s : strings) {
println s
}