Kotlin List sortedByDescending()
Syntax & Examples
Syntax of List.sortedByDescending()
The syntax of List.sortedByDescending() extension function is:
fun <T, R : Comparable<R>> Iterable<T>.sortedByDescending( selector: (T) -> R? ): List<T>
This sortedByDescending() extension function of List returns a list of all elements sorted descending according to natural sort order of the value returned by specified selector function.
✐ Examples
1 Example
In this example,
- We define a data class
Person
with propertiesname
andage
. - We create a list of
Person
objects namedlist
with ages25, 30, 20
. - We use
sortedByDescending
to sort the list byage
in descending order. - The sorted list is stored in
sortedList
. - We print
sortedList
usingprintln()
.
Kotlin Program
fun main(args: Array<String>) {
data class Person(val name: String, val age: Int)
val list = listOf(Person("Alice", 25), Person("Bob", 30), Person("Charlie", 20))
val sortedList = list.sortedByDescending { it.age }
println(sortedList)
}
Output
[Person(name=Bob, age=30), Person(name=Alice, age=25), Person(name=Charlie, age=20)]
2 Example
In this example,
- We create a list of characters named
list
containing elements'b', 'a', 'd', 'c', 'e'
. - We use
sortedByDescending
with the identity function{ it }
to sort the list in descending order. - The sorted list is stored in
sortedList
. - We print
sortedList
usingprintln()
.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf('b', 'a', 'd', 'c', 'e')
val sortedList = list.sortedByDescending { it }
println(sortedList)
}
Output
[e, d, c, b, a]
3 Example
In this example,
- We create a list of strings named
list
containing elements"banana", "apple", "date", "cherry"
. - We use
sortedByDescending
with the length function{ it.length }
to sort the list in descending order based on string length. - The sorted list is stored in
sortedList
. - We print
sortedList
usingprintln()
.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("banana", "apple", "date", "cherry")
val sortedList = list.sortedByDescending { it.length }
println(sortedList)
}
Output
[banana, cherry, apple, date]
Summary
In this Kotlin tutorial, we learned about sortedByDescending() extension function of List: the syntax and few working examples with output and detailed explanation for each example.