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()
For a list of maps, if you want to sort on the value of a particular map property, pass a closure that returns the property to use for sorting. The following example shows how to sort a 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 }
For a map of maps, the approach is similar but since the closure is passed a map entry key/value pair, this use case requires accessing the 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 }
If you need more control over the sorting, you can pass a closure that accepts two parameters and returns:
  • 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
The simplest way to implement a comparator closure is to use the Groovy "compare to" operator (<=>). 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.