
- Kotlin - Home
- Kotlin - Overview
- Kotlin - Environment Setup
- Kotlin - Architecture
- Kotlin - Basic Syntax
- Kotlin - Comments
- Kotlin - Keywords
- Kotlin - Variables
- Kotlin - Data Types
- Kotlin - Operators
- Kotlin - Booleans
- Kotlin - Strings
- Kotlin - Arrays
- Kotlin - Ranges
- Kotlin - Functions
- Kotlin Control Flow
- Kotlin - Control Flow
- Kotlin - if...Else Expression
- Kotlin - When Expression
- Kotlin - For Loop
- Kotlin - While Loop
- Kotlin - Break and Continue
- Kotlin Collections
- Kotlin - Collections
- Kotlin - Lists
- Kotlin - Sets
- Kotlin - Maps
- Kotlin Objects and Classes
- Kotlin - Class and Objects
- Kotlin - Constructors
- Kotlin - Inheritance
- Kotlin - Abstract Classes
- Kotlin - Interface
- Kotlin - Visibility Control
- Kotlin - Extension
- Kotlin - Data Classes
- Kotlin - Sealed Class
- Kotlin - Generics
- Kotlin - Delegation
- Kotlin - Destructuring Declarations
- Kotlin - Exception Handling
Kotlin Array - sortedByDescending() Function
The Kotlin array sortedByDescending() function is used to return a list containing all elements sorted in descending order according to the natural sort order of the value returned by specified selector function.
Syntax
Following is the syntax of Kotlin array sortedByDescending() function −
inline fun <T, R : Comparable<R>> Array<out T>.sortedByDescending( crossinline selector: (T) -> R? ): List<T>
Parameters
This function accepts selector as a parameters, which represents a function that defines the criteria for sorting.
Return value
This function returns a list containing all elements in descending order.
Example 1
The following is a basic example to demonstrate the use of sortedByDescending() function −
fun main(args: Array<String<){ var arr = arrayOf<Int>(2, 4, 5, 6, 1) val list = arr.sortedByDescending({it}) println("Descending list: $list") }
Output
The above code generate following output −
Descending list: [6, 5, 4, 2, 1]
Example 2
In this example we use the sortedByDescending() function to sort the elements of an array in descending order according to length −
fun main(args: Array<String>){ var arr = arrayOf<String>("This", "is", "tutorialspoint", "India") val list = arr.sortedByDescending({it.length}) println("Descending list:") println(list) }
Output
Following is the output −
Descending list: [tutorialspoint, India, This, is]
Example 3
The below example creates a person class that takes the person's age as argument. We then use sortedByDescending() function to sort the age of the person in descending order −
class Person(var age: Int) { override fun toString(): String { return "$age" } } fun main(args: Array<String>) { val p1 = Person(24) val p2 = Person(29) val p3 = Person(30) val listOfage = arrayOf(p1, p2, p3) val sorted_age_list = listOfage.sortedByDescending { it.age } print("Descending ages:") println(sorted_age_list) }
Output
Following is the output −
Descending ages: [30, 29, 24]