kotlin sortedby descending
The sortedByDescending
function is used to sort elements in a collection in descending order based on the result of the given selector function. It returns a new list of elements sorted in the specified order.
Here's an example:
data class Person(val name: String, val age: Int)
fun main() {
val people = listOf(Person("Alice", 29), Person("Bob", 31), Person("Charlie", 25))
val sortedPeople = people.sortedByDescending { it.age }
println(sortedPeople)
}
In this example, we have a list of Person
objects. We use the sortedByDescending
function with a selector function { it.age }
to sort the list of people in descending order based on their age. The resulting sortedPeople
list will contain the Person
objects sorted by age in descending order.