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

时间:2013-12-04 21:29:13

标签: arrays sorting input 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

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

1 个答案:

答案 0 :(得分:25)

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