Kotlin – Sort Array of Strings

Sort array of strings in Kotlin

To sort a given array of strings in Kotlin, you can use Array.sort() function.

Call sort() function on given array of strings strArray.

strArray.sort()

The function sorts the array in-place.

If you would like to sort the array in descending order, you may use Array.sortDescending() function as shown in the following.

strArray.sortDescending()

Note: The strings are sorted lexicographically, i.e., in the order of words in a dictionary.

Examples

Sort array of strings in ascending order

In the following program, we take an array of strings in strArray variable, say some fruit names, and sort the strings in the array in ascending order using sort() function.

Kotlin Program

fun main() {
    val strArray = arrayOf("cherry", "mango", "fig", "apple")
    strArray.sort()
    println(strArray.contentToString())
}

Output

[apple, cherry, fig, mango]

Sort array of strings in descending order

In the following program, we sort the strings in the array in descending order using sortDescending() function.

Kotlin Program

fun main() {
    val strArray = arrayOf("cherry", "mango", "fig", "apple")
    strArray.sortDescending()
    println(strArray.contentToString())
}

Output

[mango, fig, cherry, apple]