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

18

我最近在学习使用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个回答

40

sort() 是你的好朋友。

country.sort() 会按字母顺序对 country 进行排序,同时更改 countrycountry.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']

哇,好简单啊。我越来越喜欢Groovy了。谢谢! - Inquirer21
6
若您想按字母顺序排序(即不区分大小写,根据您所在地区的规则),而不仅是按Unicode代码点排序,请使用 country.sort(java.text.Collator.instance) - ataylor
@ataylor 哦,那很棒! - doelleri
有没有一种简单的方法可以按字母顺序降序排序(z..a)? - user3105453
5
你可以使用.sort().reverse()或自定义闭包一步完成反向排序。 - doelleri

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接