In this tutorial, you shall learn how to sort an array of strings in Kotlin, in ascending or descending order using Array.sort() method or Array.sortDescending() method, with examples.

Kotlin – Sort Array of Strings

To sort an Array of Strings in Kotlin, use Array.sort() method. sort() method sorts the calling array in-place in ascending order. To sort String Array in descending order, call sortDescending() method on this Array.

Ascending or Descending order of strings is done lexicographically. Meaning, "a" is less than "b", "b" is less than "c", and so on. ASCII values of characters are considered while comparing the strings.

Syntax

The syntax to call sort() method on Array arr is

</>
Copy
arr.sort()

The syntax to call sortDescending() method on Array arr is

</>
Copy
arr.sortDescending()

Examples

Sort in Ascending Order

In the following example, we take an array of strings, and sort them in ascending order in-place using sort() method.

Main.kt

</>
Copy
fun main(args: Array<String>) {
    val arr = arrayOf("b", "e", "a", "f", "d", "c")
    arr.sort()
    for (x in arr) print("$x  ")
}

Output

a  b  c  d  e  f  

Sort in Descending Order

In the following example, we take an array of strings, and sort them in descending order in-place using sortDescending() method.

Main.kt

</>
Copy
fun main(args: Array<String>) {
    val arr = arrayOf("b", "e", "a", "f", "d", "c")
    arr.sortDescending()
    for (x in arr) print("$x  ")
}

Output

f  e  d  c  b  a  

Conclusion

In this Kotlin Tutorial, we learned how to sort a String Array in ascending or descending order using sort() or sortDescending() methods respectively, with examples.