Подтвердить что ты не робот

Сортировка массива строк по алфавиту в groovy

Итак, я учился работать с массивами в Groovy. Мне интересно, как сортировать массив строк по алфавиту. Мой код в настоящее время принимает строковый ввод от пользователя и печатает их в порядке и в обратном порядке:

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

Как я могу распечатать их в алфавитном порядке?

4b9b3361

Ответ 1

sort() - ваш друг.

country.sort() сортирует country в алфавитном порядке, мутируя country в процессе. country.sort(false) сортирует country в алфавитном порядке, возвращая отсортированный список.

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']