Sort an array of strings alphabetically in groovy

Viewed 39143

So I have been learning to work with arrays in Groovy. I am wondering how to sort an array of strings alphabetically. My code currently takes string input from the user and prints them out in order and reverse order:

System.in.withReader {
    def country = []
      print 'Enter your ten favorite countries:'
    for (i in 0..9)
        country << it.readLine()
        print 'Your ten favorite countries in order/n'
    println country            //prints the array out in the order in which it was entered
        print 'Your ten favorite countries in reverse'
    country.reverseEach { println it }     //reverses the order of the array

How would I go about printing them out alphabetically?

1 Answers

sort() is your friend.

country.sort() will sort country alphabetically, mutating country in the process. country.sort(false) will sort country alphabetically, returning the sorted list.

def country = ['Ireland', 'Iceland', 'Hungary', 'Thailand']
assert country.sort() == ['Hungary', 'Iceland', 'Ireland', 'Thailand']
assert country == ['Hungary', 'Iceland', 'Ireland', 'Thailand']

country = ['Ireland', 'Iceland', 'Hungary', 'Thailand']
assert country.sort(false) == ['Hungary', 'Iceland', 'Ireland', 'Thailand']
assert country == ['Ireland', 'Iceland', 'Hungary', 'Thailand']
Related