Kotlin Array - sortedDescending() Function



The Kotlin array sortedDescending() function is used to return a list containing elements of an array in descending order according to their natural sort order.

This function creates a new sorted descending list without modifying the original array. It only sorts data of the same type and returns an error if the data types are different.

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 sortedDescending() function −

fun <T : Comparable<T>> Array<out T>.sortedDescending(): List<T>

Parameters

This function does not accepts any parameters −

Return value

This function returns a list containing sorted elements of this array in descending order.

Example 1

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

fun main(args: Array<String>){
   var arr = arrayOf<Int>(2, 4, 5, 6, 1)
   
   // sort the array element in descending.        
   val list = arr.sortedDescending()   
   println("list: $list") 
}

Output

The above code generate following output −

list: [6, 5, 4, 2, 1]

Example 2

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

fun main(args: Array<String>){
   var arr = arrayOf<String>("Hello", "hyderabad", "tutorialspoint", "India")
        
   val list = arr.sortedDescending()   
   println("Descending array list: $list")   
}

Output

Following is the output −

Descending array list: [tutorialspoint, hyderabad, India, Hello]

Example 3

The below example creates an array of person object. We then use sortedDescending() function to sort the array in descending order by their age −

data class Person(val name: String, val age: Int) : Comparable<Person> {
   override fun compareTo(other: Person): Int {
      return this.age.compareTo(other.age)
   }
}
fun main() {
   val people = arrayOf(
      Person("Ram", 42),
      Person("Lakashman", 25),
      Person("Bharat", 35),
      Person("Krishna", 28),
      Person("Arjun", 40)
   )

   println("Original array:")
   people.forEach { println("Name: ${it.name}, Age: ${it.age}") }

   // Sort the array in descending order
   val sortedPeople = people.sortedDescending()

   println("\nSorted array in descending order by age:")
   sortedPeople.forEach { println("Name: ${it.name}, Age: ${it.age}") }
}

Output

The above code produce following output −

Original array:
Name: Ram, Age: 42
Name: Lakashman, Age: 25
Name: Bharat, Age: 35
Name: Krishna, Age: 28
Name: Arjun, Age: 40

Sorted array in descending order by age:
Name: Ram, Age: 42
Name: Arjun, Age: 40
Name: Bharat, Age: 35
Name: Krishna, Age: 28
Name: Lakashman, Age: 25
kotlin_arrays.htm
Advertisements