Sorting Items in a Collections
To sort the items in a collection, use the sort() function. If the collection is a simple list then its items will be sorted ascending by their natural ordering.
For example, this line will sort the list of names in alphabetical order. The collection you invoke it on is updated to reflect the sorted ordering:
def names = ['Zane','Jasmine','Abigail','Adam']
names.sort()
users
collection based on the number of
accesses
a user has
made.def users = [
[userid:'smuench', name:'Steve', badge:'A123', accesses: 135],
[userid:'jevans', name:'Joe', badge:'B456', accesses: 1001],
[userid:'sburns', name:'Steve', badge:'C789', accesses: 52]
]
// Sort the list of maps based on the accesses property of each map
users.sort { it.accesses }
value
property of
the map entry before referencing its accesses
property as shown here.
def users = [
'smuench':[name:'Steve', badge:'A123', accesses: 135],
'jevans':[name:'Joe', badge:'B456', accesses: 1001],
'sburns':[name:'Steve', badge:'C789', accesses: 52]
]
// Sort the map of maps based on the accesses property of map entry's value
users.sort { it.value.accesses }
-
0
— if they are equal -
-1
— if the first parameter is less than the second parameter -
1
— if the first parameter is greater than the second parameter
<=>
). In the example below, the two-parameter closure
uses this operator to return the appropriate integer based on comparing the value of the
accesses
property of the the first map entry's value with the
corresponding value of the same property on the second map entry's
value.// Sort map of maps by comparing the accesses property of map entry's value
users.sort { a, b -> a.value.accesses <=> b.value.accesses }
To reverse the sort order to be descending if needed, simply swap the roles of the
two parameters passed to the closure. For example, to sort the user list descending by
number of accesses, as shown below, swap the a
and b
parameters on the right side of the arrow:
// Sort map of maps DESCENDING by comparing the accesses property of map entry's value
users.sort { a, b -> b.value.accesses <=> a.value.accesses }
If your sorting needs are more complex, you can implement the comparator closure in any way you need to, so long as it returns one of the three expected integer values.