Kotlin Array - sortedArrayDescending() Function



The Kotlin array sortedArrayDescending() function creates a new array sorted in descending order without modifying the original. It returns it with all elements sorted descending according to their natural sort 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 sortedArrayDescending() function −

fun <T : Comparable<T>> Array<T>.sortedArrayDescending(): Array<T>

Parameters

This function does not accepts any parameters −

Return value

This function returns an array containing elements of this array or original array in descending order.

Example 1

Following is a basic example to demonstrate the use of sortedArrayDescending() function −

fun main(args: Array<String&gt){
   var arr = arrayOf<Int&gt(2, 4, 5, 6, 1)
   
   // sort the array element in descending order.        
   var sorted_array = arr.sortedArrayDescending()
   print("Sorted array: ")
   println(sorted_array.joinToString()) 
}

Output

The above code generate following output −

Sorted array: 6, 5, 4, 2, 1

Example 2

Here is another example demonstrating the use of the sortedArrayDescending() function with an array of strings representing names −

fun main(args: Array<String>) {
   val names = arrayOf("Zara", "Pawan", "aishwarya", "John", "Bimly")

   // Get a new sorted descending array
   val sortedNames = names.sortedArrayDescending()

   println("Original array: ${names.joinToString(", ")}")
   println("Descending array: ${sortedNames.joinToString(", ")}")
}

Output

Following is the output −

Original array: Zara, Pawan, aishwarya, John, Bimly
Descending array: aishwarya, Zara, Pawan, John, Bimly

Example 3

The below example creates an array. We then use sortedArrayDescending() function to sort in descending order according to alphabets −

fun main(args: Array<String>) {
   val alphabets = arrayOf('b', 'a', 'e', 'm', 'n')

   // Get a new sorted array
   val sorted = alphabets.sortedArrayDescending()

   println("Original alphabets: ${alphabets.joinToString(", ")}")
   println("Sorted alphabets: ${sorted.joinToString(", ")}")
}

Output

Following is the output −

Original alphabets: b, a, e, m, n
Sorted alphabets: n, m, e, b, a
kotlin_arrays.htm
Advertisements