简体   繁体   中英

sorting using weird groovy code

I'm a beginner at groovy and I can't seem to understand this code. 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? 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)

The code is using 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.

    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 )

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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