所以我一直在学习使用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
我如何按字母顺序打印出来?
答案 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']