Kotlin Array.sortDescending()

Kotlin Array.sortDescending() function

In Kotlin, the Array.sortDescending() function is used to sort the elements of an array in descending order. This function modifies the original array in-place, resulting in a new order of elements.

This can be useful when you want to organize the elements of an array in a specific order, such as arranging a list of numbers, strings, or custom objects in descending order.

In this tutorial, we’ll explore the syntax of the Array.sortDescending() function and provide examples of its usage in Kotlin arrays.

Syntax

The syntax of the Array.sortDescending() function is:

fun <T : Comparable<T>> Array<out T>.sortDescending()

The sortDescending() function is an extension function specifically designed for arrays of elements that implement the Comparable interface. It modifies the original array in-place.

Examples for sortDescending() function

1. Sorting an Array of Numbers in Descending order

In this example, we’ll use sortDescending() to sort the elements of an array of numbers numbersArray in descending order.

Kotlin Program

fun main() {
    val numbersArray = intArrayOf(5, 2, 8, 1, 7)
    println("Original Array\n${numbersArray.contentToString()}")

    // Sorting the array of numbers in descending order
    numbersArray.sortDescending()

    // Printing the sorted array
    println("Sorted Array\n${numbersArray.contentToString()}")
}

Output

Original Array
[5, 2, 8, 1, 7]
Sorted Array
[8, 7, 5, 2, 1]

2. Sorting an Array of Strings in Descending order

In this example, we’ll use sortDescending() to sort the elements of an array of strings in lexicographical descending order.

Kotlin Program

fun main() {
    val wordsArray = arrayOf("banana", "kiwi", "apple", "mango")
    println("Original Array\n${wordsArray.contentToString()}")

    // Sorting the array of strings
    wordsArray.sortDescending()

    // Printing the sorted array
    println("Sorted Array\n${wordsArray.contentToString()}")
}

Output

Original Array
[banana, kiwi, apple, mango]
Sorted Array
[apple, banana, kiwi, mango]

Summary

In this tutorial, we’ve covered the Array.sortDescending() function in Kotlin, its syntax, and how to use it to sort the elements of an array in descending order.