对于比较器的排序语法如何工作,我有点困惑:
m.sort {a,b - > a.value => b.value}有人可以解释 { 和} 是什么意思? 当> Closure 被使用时排序 有两个参数,它像一个传统的 比较 。也就是说,对于在排序过程中进行的每个比较,在两个元素 a 和 b 之间进行比较,返回一个负整数,零或一个正整数,因为第一个参数小于,等于或大于第二个。
在您的特定场景中,比较结果是使用太空船运营商 < = > 。换句话说,您正在按升序顺序排列元素。
例如,如果您有列表 [3,2,1] ,使用该排序的结果将 m.sort {a,b - > a.value => b.value} 大致等于使用下面的 compare 函数: int compare(a,b){ if(a< b){ return -1; } else else if(a> b){ return 1; } else { return 0; } }
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?
解决方案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; } }