Skip to main content
ubuntuask.com

Back to all posts

How to Sort A List In Groovy?

Published on
3 min read

Table of Contents

Show more
How to Sort A List In Groovy? image

To sort a list in Groovy, you can use the sort() method on a list object. This method will sort the elements in the list in natural order. You can also use the sort method with a closure to define a custom sorting order. Another option is to use the sort method with a comparator to specify the criteria for sorting the elements in the list. Additionally, you can use the sort method to sort the list in descending order by passing in the reverse: true parameter. Overall, sorting a list in Groovy is a straightforward process with several options available to customize the sorting order.

What is the default sorting order of a list in Groovy?

The default sorting order of a list in Groovy is according to the natural ordering of its elements, which is typically either ascending order for numbers or lexicographical order for strings.

How to sort a list of objects based on a specific property in Groovy?

In Groovy, you can use the sort method with a closure to sort a list of objects based on a specific property.

For example, let's say you have a list of objects of the class Person with a property age. You can sort the list of Person objects based on the age property as follows:

class Person { String name int age

Person(String name, int age) {
    this.name = name
    this.age = age
}

}

def persons = [ new Person('Alice', 30), new Person('Bob', 25), new Person('Charlie', 35) ]

persons.sort { it.age }

println persons

In this example, the persons.sort { it.age } line sorts the list of Person objects based on the age property in ascending order. If you want to sort the list in descending order, you can use persons.sort { -it.age }.

You can also sort the list based on multiple properties by chaining sort calls. For example, to first sort by age in ascending order and then by name in descending order, you can use the following code:

persons.sort { it.age }.sort { -it.name }

What is the purpose of using the reverse() method in Groovy?

The purpose of using the reverse() method in Groovy is to reverse the order of elements in an array, list or collection. This method can be used to easily flip the sequence of elements, which can be useful in certain algorithms, data processing, or visual presentation of data.