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

Inq*_*r21 14 arrays sorting groovy input

所以我一直在学习使用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
Run Code Online (Sandbox Code Playgroud)

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

doe*_*eri 26

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']
Run Code Online (Sandbox Code Playgroud)

  • 如果要按字母顺序排序(即不区分大小写,根据语言环境的规则)而不是仅使用Unicode代码点,请使用`country.sort(java.text.Collat​​or.instance)`. (5认同)
  • @ user3105453要么是`.sort().reverse()`,要么你可以使用自定义闭包在一个步骤中以相反的顺序排序. (3认同)