Kotlin Array - sortByDescending() Function



The Kotlin array sortByDescending() function is used to sort an array of elements in place based on natural sort order of the value returned by specified selector function.

The elements will be returned by this function will be in descending order.

The sort is stable. It means that equal elements preserve their order relative to each other after sorting.

Syntax

Following is the syntax of Kotlin array sortByDescending() function −

inline fun <T, R : Comparable<R>> Array<out T>.sortByDescending(
   crossinline selector: (T) -> R?)

Parameters

This function accepts selector as a parameters, which represents a function that defines the criteria for sorting.

Return value

This function does not returns any value. It only modifies the original array into descending order.

Example 1

The following is a basic example to demonstrate the use of sortByDescending() function −

fun main(args: Array<String>){
   var arr = arrayOf<Int>(2, 4, 5, 6, 1)
        
   arr.sortByDescending({it})   
   println("descending array")
   for (i in 0 until arr.size){
      println(arr.get(i))
   }   
}

Output

The above code generate following output −

descending array
6
5
4
2
1

Example 2

Now here, we create an array of string. We then use sortByDescending() function to sort the elements in descending order according to length of string −

fun main(args: Array<String>){
   var arr = arrayOf<String>("This", "is", "tutorialspoint", "India")
        
   arr.sortByDescending({it.length})   
   println("Descending order:")
   for (i in 0 until arr.size){
      println(arr.get(i))
   }
}

Output

Following is the output −

Sorted array:
is
This
India
tutorialspoint

Example 3

The below example uses sortByDescending() function to sort the elements in descending order −

fun main(args: Array<String>){
   var arr = arrayOf<Char>('t', 'u', 't', 'o', 'r', 'i', 'a', 'l', 's', 'p', 'o', 'i', 'n', 't')
   
   // sort the array
   arr.sortByDescending({it})   
   println("Descending order:")
   println(arr.joinToString())
}

Output

Following is the output −

Descending order:
u, t, t, t, s, r, p, o, o, n, l, i, i, a
kotlin_arrays.htm
Advertisements