Close

Groovy Operators - Spaceship Operator

[Last Updated: Dec 18, 2018]

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
}

Output

fig
pie
apple
banana
orange

Example Project

Dependencies and Technologies Used:

  • Groovy 2.5.3
  • JDK 9.0.1
Groovy - Spaceship Operator Select All Download
  • groovy-spaceship-operator
    • src
      • SpaceshipExample.groovy

    See Also