groovy sort with comparator syntax

42,035

Solution 1

When the Closure used by sort has two parameters, it acts like a traditional Comparator. That is, for each comparison that is done during the sort, between two elements a and b, it returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

In your particular scenario, the comparison is the result of using the spaceship operator <=>. In other words, you are effectively sorting your elements in ascending order.

For example, if you had the list [ 3, 2, 1 ], the result of using that sort would be [ 1, 2, 3 ].

Thus, m.sort{a,b -> a.value <=> b.value} is roughly the equivalent of using the following compare function:

int compare(a, b) {
  if (a < b) {
    return -1;
  } else if (a > b) {
    return 1;
  } else {
    return 0;
  }
}

Solution 2

The spaceship operator <=> is an overloaded operator and represents compareTo(). Basically a<=>b is the same as a.compareTo(b)

The example that you gave is using the sort() function with a closure (like lambda in Java8). The syntax for it is the following:

.method{closureParameters -> statements}

So your example is using the sort() function with a closure, inside that closure you use the spaceship (comparator) operator

More about operator overloading here

Share:
42,035

Related videos on Youtube

F21
Author by

F21

Founder Boostport.

Updated on July 09, 2022

Comments

  • F21
    F21 almost 2 years

    I am just getting my feet wet with gremlin. I understand that gremlin is based on groovy. I found the documentation here, but I am still not sure what the syntax means.

    I am a bit confused as to how the syntax of sort with a comparator works:

    m.sort{a,b -> a.value <=> b.value}
    

    Could someone explain what all the different bits between the { and } mean?

  • F21
    F21 over 11 years
    So, the a,b ->, simply passes the values a and b to the comparator?
  • João Silva
    João Silva over 11 years
    @F21: Yes, sort of. It's like a function that takes two parameters and is used to sort according to the function body which returns the spaceship operator.
  • redDevil
    redDevil over 9 years
    i didnt get what is a <=> spaceship operator. Wiki was of not much help