4

How to sort the following string array in kotlin in alphabetic order?

val array = arrayOf("abc","bcd","xyz","ghi","acd")
1
  • 2
    it annoys me when people downvote new users without explaining why. Your question has been downvoted because questions on StackOverflow should be more specific. So you should show what you've tried and why it didn't wok. Commented Dec 27, 2017 at 9:59

2 Answers 2

12

To sort the same array we can use

array.sort()

This inbuilt method will sort in alphabetic order. We can also sort Int Array and other array types using inbuilt sort() method

To sort an array without changing the original we can use

val array = arrayOf("abc","bcd","xyz","ghi","acd")
val sorted = array.sortedArray()

as mentioned above answer by s1m0nw1

Sign up to request clarification or add additional context in comments.

Comments

6

It might be interesting to not modify the original array. Therefore sortedArray can be used:

val array = arrayOf("abc","bcd","xyz","ghi","acd")
val sorted = array.sortedArray()

println(array.contentDeepToString())
println(sorted.contentDeepToString())
//[abc, bcd, xyz, ghi, acd]
//[abc, acd, bcd, ghi, xyz]

It creates a new Array without modifying the original.

Otherwise, the original string array can be modified and sorted with sort().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.