To sort a list in descending order in Kotlin, you can use the sortedByDescending
method.
In this example,
numbers
with integer values.sortedByDescending
method on the numbers
list to sort it in descending order.sortedByDescending
method returns a new list sorted in descending order, leaving the original list unchanged.fun main() {
val numbers = listOf(5, 2, 8, 1, 3)
val sortedNumbers = numbers.sortedByDescending { it }
println("Sorted list in descending order: $sortedNumbers")
}
Sorted list in descending order: [8, 5, 3, 2, 1]
In this example,
words
with string values.sortedByDescending
method on the words
list to sort it in descending order based on string length.sortedByDescending
method returns a new list sorted in descending order, leaving the original list unchanged.fun main() {
val words = listOf("banana", "apple", "cherry")
val sortedWords = words.sortedByDescending { it.length }
println("Sorted list in descending order: $sortedWords")
}
Sorted list in descending order: [banana, cherry, apple]
In this tutorial, we learned How to Sort a List in Descending Order in Kotlin language with well detailed examples.