Sorting in Groovy
Our example demonstrates sorting for built-in types in Groovy. We’ll look at sorting for strings and integers.
// Groovy's built-in sorting methods work for any
// Comparable type, which includes strings and numbers.
def main() {
// An example of sorting strings
def strs = ["c", "a", "b"]
strs.sort()
println "Strings: $strs"
// An example of sorting integers
def ints = [7, 2, 4]
ints.sort()
println "Ints: $ints"
// We can also check if a list is already in sorted order
def s = ints == ints.sort()
println "Sorted: $s"
}
main()
Groovy provides built-in sorting methods for lists and other collections. The sort()
method can be called directly on a list to sort it in place.
To run the program, save it as sorting.groovy
and use the groovy
command:
$ groovy sorting.groovy
Strings: [a, b, c]
Ints: [2, 4, 7]
Sorted: true
In Groovy, the sort()
method uses natural ordering for comparable types like strings and numbers. For custom sorting, you can provide a closure to the sort()
method, which we’ll explore in a future example.
Unlike some other languages, Groovy doesn’t require a separate package for basic sorting operations, as these are built into the core language features.