在groovy中按字母顺序对字符串数组进行排序

时间:2022-04-15 07:42:31

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:

所以我一直在学习使用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

How would I go about printing them out alphabetically?

我将如何按字母顺序打印出来?

1 个解决方案

#1


23  

sort() is your friend.

sort()是你的朋友。

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

country.sort()将按字母顺序对国家进行排序,在此过程中改变国家/地区。 country.sort(false)将按字母顺序对国家进行排序,返回已排序的列表。

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

#1


23  

sort() is your friend.

sort()是你的朋友。

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

country.sort()将按字母顺序对国家进行排序,在此过程中改变国家/地区。 country.sort(false)将按字母顺序对国家进行排序,返回已排序的列表。

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