In this tutorial, you shall learn how to sort a given array in descending order in Kotlin using Array.sortedDescending() method, with examples.
Kotlin Array – Sort in Descending Order
To sort an Array in descending order in Kotlin, use Array.sortDescending() method. This method sorts the calling array in descending order in-place. To return the sorted array and not modify the original array, use Array.sortedDescending() method.
Examples
1. Sort given array of integers in descending order
In the following program, we take an array of integers, and sort them in descending order using Array.sortDescending() method.
Main.kt
fun main(args: Array<String>) {
val arr = arrayOf(2, 4, 1, 3, 6, 5)
arr.sortDescending()
for (x in arr) print("$x ")
}
Output
6 5 4 3 2 1
2. Sort given array of strings in descending order
In the following example, we take an array of Strings, and sort them in descending order.
Main.kt
fun main(args: Array<String>) {
val arr = arrayOf("apple", "fig", "banana", "kiwi")
arr.sortDescending()
for (x in arr) print("$x ")
}
Output
kiwi fig banana apple
Conclusion
In this Kotlin Tutorial, we learned how to sort an Array in descending order, in Kotlin programming language, with examples.