Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

groovy sort with comparator syntax

Tags:

sorting

groovy

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?

like image 355
F21 Avatar asked Sep 25 '12 00:09

F21


People also ask

How do I sort a map in groovy?

Maps don't have an order for the elements, but we may want to sort the entries in the map. Since Groovy 1.7. 2 we can use the sort() method which uses the natural ordering of the keys to sort the entries. Or we can pass a Comparator to the sort() method to define our own sorting algorithm for the keys.


1 Answers

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;   } } 
like image 77
João Silva Avatar answered Sep 20 '22 15:09

João Silva