简体   繁体   English

使用奇怪的groovy代码进行排序

[英]sorting using weird groovy code

I'm a beginner at groovy and I can't seem to understand this code. 我是groovy的初学者,我似乎无法理解这段代码。 Can you please tell me how does this code operate? 你能告诉我这段代码是如何运作的吗?

def list = [ [1,0], [0,1,2] ]
list = list.sort { a,b -> a[0] <=> b[0] }
assert list == [ [0,1,2], [1,0] ]

what I know is the second line should return the value of 1 because of the spaceship operator but what is the use of that? 我所知道的是,由于宇宙飞船运营商,第二行应该返回值1,但是它的用途是什么? and what type of sort is this? 这是什么类型的? (there are 6 sort methods in the gdk api and i'm not really sure which is one is used here) (gdk api中有6种排序方法,我不确定这里使用的是哪种方法)

The code is using Collection#sort(Closure) . 代码使用Collection#sort(Closure) Notice that this method has two variants: 请注意,此方法有两种变体:

  1. If the closure is binary (ie it takes two parameters), sort uses it as the typical comparator interface: it should return an negative integer, zero or a positive integer when the first parameter is less than, equal, or grater than the second parameter respectively. 如果闭包是二进制的(即它需要两个参数), sort将它用作典型的比较器接口:当第一个参数小于,等于或大于第二个参数时,它应返回负整数,零或正整数分别。

    This is the variant that is being used in that piece of code. 这是在该段代码中使用的变体。 It is comparing the elements of the list, which are, in turn, lists, by their first element. 它通过第一个元素比较列表的元素,而列表的元素依次列出。

  2. If the closure is unary (ie it takes only one parameter) it is used to generate the values that are then going to be used for comparison (in some languages this is called a "key" function). 如果闭包是一元的(即它只需要一个参数),它将用于生成随后将用于比较的值(在某些语言中,这称为“键”函数)。

    Therefore, the snippet of code you posted can be rewritten as: 因此,您发布的代码片段可以重写为:

     def list = [[1,0], [0,1,2]] list = list.sort { it[0] } // or { it.first() } assert list == [[0,1,2], [1,0]] 

    Notice that using this unary-closure variant is very convenient when you want to compare the elements by some value or some "weight" that is calculated the same way for every element. 请注意,当您想要通过某个值或某些“权重”比较元素时,使用此一元闭包变量非常方便,该权重对每个元素的计算方式相同。

The sort in your code snippet uses the comparator argument method call - see http://groovy.codehaus.org/groovy-jdk/java/util/Collection.html#sort(java.util.Comparator ) 代码段中的sort使用比较器参数方法调用 - 请参阅http://groovy.codehaus.org/groovy-jdk/java/util/Collection.html#sort(java.util.Comparator

So, you are sorting the collection using your own comparator. 因此,您使用自己的比较器对集合进行排序。 Now the comparator simply uses the first element of the inner collection to decide the order of the outer collection. 现在比较器只使用内部集合的第一个元素来决定外部集合的顺序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM