How to sort list in Groovy?

Sorting a list is one of the most popular operations you can do on collections.
In this blog post, I show you how you can sort a list of random elements using Groovy programming language.

Sort numbers in the ascending order

1
assert [9, 4, 2, 10, 9, 3, 4].sort() == [2, 3, 4, 4, 9, 9, 10]

Sort numbers in the descending order

1
assert [9, 4, 2, 10, 9, 3, 4].sort().reverse() == [10, 9, 9, 4, 4, 3, 2]

Sort names alphabetically

1
2
3
def names = ['Joe', 'Jane', 'Adam', 'Mary', 'Betty', 'Zoe']

assert names.sort() == ['Adam', 'Betty', 'Jane', 'Joe', 'Mary', 'Zoe']

Sort names by length

1
2
3
def names = ['Joe', 'Jane', 'Adam', 'Mary', 'Betty', 'Zoe']

assert names.sort { a, b -> a.length() <=> b.length() } == ['Joe', 'Zoe', 'Adam', 'Jane', 'Mary', 'Betty']

Sort names by length and descending alphabetical order

1
2
3
def names = ['Joe', 'Jane', 'Adam', 'Mary', 'Betty', 'Zoe']

assert names.sort { a, b -> a.length() <=> b.length() ?: b <=> a } == ['Zoe', 'Joe', 'Mary', 'Jane', 'Adam', 'Betty']

Sort objects by id

1
2
3
4
5
6
7
def categories = [
[id: 10, name: "Groovy Cookbook"],
[id: 2, name: "Newest posts"],
[id: 7, name: "Something else"]
]

assert categories.sort { it.id }.name == ['Newest posts', 'Something else', 'Groovy Cookbook']
Share