So I have been learning to work with arrays in Groovy. I am wondering how to sort an array of strings alphabetically. My code currently takes string input from the user and prints them out in order and reverse order:
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
How would I go about printing them out alphabetically?
JavaScript Array sort() The sort() sorts the elements of an array. The sort() overwrites the original array. The sort() sorts the elements as strings in alphabetical and ascending order.
To sort a String array in Java, you need to compare each element of the array to all the remaining elements, if the result is greater than 0, swap them.
sort()
is your friend.
country.sort()
will sort country
alphabetically, mutating country
in the process.
country.sort(false)
will sort country
alphabetically, returning the sorted list.
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With