Skip to content
DeveloperMemos

How to Sort an Array of Strings Alphabetically in Kotlin

Kotlin, Array, String, Sort1 min read

Sorting an array of strings alphabetically in Kotlin is a simple task that can be accomplished using the built-in sort() function. Here's how it works:

1val words = arrayOf("cherry", "apple", "blueberry")
2words.sort()

This will sort the words array in ascending alphabetical order, so that it becomes ["apple", "blueberry", "cherry"].

If you want to sort the array in descending order, you can use the sortDescending() function instead:

1words.sortDescending()

This will give you the array ["cherry", "blueberry", "apple"].

You can also use the sorted() function to sort an array and return a new, sorted array, leaving the original array unchanged. For example:

1val sortedWords = words.sorted()

This will return a new array ["apple", "blueberry", "cherry"], while the original words array remains unchanged.

You can also specify a custom comparator function to use for sorting. For example, if you want to sort the words by length rather than alphabetically, you can use the following code:

1words.sortWith(compareBy { it.length })

This will sort the words array in ascending order by length, so that it becomes ["apple", "cherry", "blueberry"].