How to sort a string array in kotlin

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

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

Upvotes: 4

Views: 8393

Answers (2)

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

Upvotes: 12

s1m0nw1
s1m0nw1

Reputation: 81879

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().

Upvotes: 6

Related Questions