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)