groovy sort with comparator syntax

前端 未结 2 612
囚心锁ツ
囚心锁ツ 2020-12-16 10:59

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.

2条回答
  •  天涯浪人
    2020-12-16 11:02

    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;
      }
    }
    

提交回复
热议问题