Kotlin Set sortedByDescending()
Syntax & Examples
Set.sortedByDescending() extension function
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.
Syntax of Set.sortedByDescending()
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.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
selector | required | A function that takes an element and returns the value to be compared. |
Return Type
Set.sortedByDescending() returns value of type List
.
✐ Examples
1 Sorting a set of integers in descending order
Using sortedByDescending() to sort a set of integers in descending order.
For example,
- Create a set of integers.
- Use sortedByDescending() with a selector function that returns the integer itself.
- Print the resulting sorted list.
Kotlin Program
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
val sortedNumbers = numbers.sortedByDescending { it }
println(sortedNumbers)
}
Output
[5, 4, 3, 2, 1]
2 Sorting a set of strings by their length in descending order
Using sortedByDescending() to sort a set of strings by their length in descending order.
For example,
- Create a set of strings.
- Use sortedByDescending() with a selector function that returns the length of each string.
- Print the resulting sorted list.
Kotlin Program
fun main() {
val strings = setOf("one", "three", "two")
val sortedStrings = strings.sortedByDescending { it.length }
println(sortedStrings)
}
Output
[three, one, two]
3 Sorting a set of custom objects by a property in descending order
Using sortedByDescending() to sort a set of custom objects by a specific property in descending order.
For example,
- Create a data class.
- Create a set of custom objects.
- Use sortedByDescending() with a selector function that returns the value of the property to be compared.
- Print the resulting sorted list.
Kotlin Program
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)
}
Output
[Person(name=Charlie, age=35), Person(name=Alice, age=30), Person(name=Bob, age=25)]
Summary
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.