The sortedByDescending() extension function in Kotlin returns a list of all elements sorted in descending order according to the natural sort order of the value returned by the specified selector function.
The syntax of Set.sortedByDescending() extension function is:
fun <T, R : Comparable<R>> Set<T>.sortedByDescending(selector: (T) -> R?): List<T>
This sortedByDescending() extension function of Set returns a list of all elements sorted descending according to natural sort order of the value returned by specified selector function.
Parameter | Optional/Required | Description |
---|---|---|
selector | required | A function that takes an element and returns the value to be compared. |
Set.sortedByDescending() returns value of type List
.
Using sortedByDescending() to sort a set of integers in descending order.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
val sortedNumbers = numbers.sortedByDescending { it }
println(sortedNumbers)
}
[5, 4, 3, 2, 1]
Using sortedByDescending() to sort a set of strings by their length in descending order.
For example,
fun main() {
val strings = setOf("one", "three", "two")
val sortedStrings = strings.sortedByDescending { it.length }
println(sortedStrings)
}
[three, one, two]
Using sortedByDescending() to sort a set of custom objects by a specific property in descending order.
For example,
data class Person(val name: String, val age: Int)
fun main() {
val people = setOf(Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35))
val sortedPeople = people.sortedByDescending { it.age }
println(sortedPeople)
}
[Person(name=Charlie, age=35), Person(name=Alice, age=30), Person(name=Bob, age=25)]
In this Kotlin tutorial, we learned about sortedByDescending() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.