使用比较器语法进行常规排序 [英] groovy sort with comparator syntax
问题描述
我刚刚被小鬼弄湿了.我知道 gremlin 是基于 groovy 的.我在这里找到了文档a>,但我仍然不确定语法是什么意思.
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?
推荐答案
当 sort
使用的 Closure
有两个参数时,它的作用就像传统的 Comparator
.也就是说,对于在排序过程中进行的每次比较,在两个元素 a
和 b
之间,它返回一个负整数、零或一个正整数作为第一个参数小于、等于或大于第二个.
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.
例如,如果您有列表 [ 3, 2, 1 ]
,则使用该排序的结果 应该是 [ 1, 2, 3 ]
.
For example, if you had the list [ 3, 2, 1 ]
, the result of using that sort would be [ 1, 2, 3 ]
.
因此,m.sort{a,b ->a.值<=>b.value}
大致相当于使用以下 compare
函数:
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;
}
}
这篇关于使用比较器语法进行常规排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!