In this tutorial, you shall learn how to sort an array of strings based on their length in Kotlin, using Array.sortBy() method, with examples.
Kotlin – Sort array of strings based on length
To sort an Array of Strings based on its length property in Kotlin, use Array.sortBy() method. sortBy() method sorts the calling array in-place in ascending order based on the selector passed as argument.
Syntax
The syntax to call sortBy() method on Array arr
is
arr.sortBy(selector: (T) -> (R))
The selector function takes element as argument and returns a value which is used for comparison between elements.
Examples
In the following example, we take an array of strings, and sort them in ascending order in-place based on length using sortBy() method.
Main.kt
fun main(args: Array<String>) {
val arr = arrayOf("banana", "kiwi", "apple")
val selector: (String) -> Int = { str -> str.length }
arr.sortBy(selector)
for (x in arr) print("$x ")
}
Output
kiwi apple banana
We can also specify the selector function directly as shown in the following program.
Main.kt
fun main(args: Array<String>) {
val arr = arrayOf("banana", "kiwi", "apple")
arr.sortBy { it.length }
for (x in arr) print("$x ")
}
Output
kiwi apple banana
Conclusion
In this Kotlin Tutorial, we learned how to sort a String Array based on string length using sortBy() method, with examples.