Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort an array of strings alphabetically in groovy

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?

like image 794
Inquirer21 Avatar asked Dec 04 '13 21:12

Inquirer21


People also ask

How do you sort an array of strings alphabetically?

JavaScript Array sort() The sort() sorts the elements of an array. The sort() overwrites the original array. The sort() sorts the elements as strings in alphabetical and ascending order.

How do you sort an array of strings?

To sort a String array in Java, you need to compare each element of the array to all the remaining elements, if the result is greater than 0, swap them.


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']
like image 89
doelleri Avatar answered Sep 23 '22 06:09

doelleri