Kotlin Array.sorted()

Kotlin Array.sorted() function

In Kotlin, the Array.sorted() function is used to obtain a List containing the elements of the original array sorted in ascending order.

Unlike Array.sort(), this function does not modify the original array; instead, it returns a new list with the sorted elements.

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

Syntax

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

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

The sorted() function is an extension function specifically designed for arrays of elements that implement the Comparable interface. It returns a new List containing the sorted elements.

Examples for Array.sorted() function

1. Sorting an Array of Numbers

In this example, we’ll use Array.sorted() to obtain a new array with the elements of given array of numbers numbersArray sorted in ascending order.

Kotlin Program

fun main() {
    val numbersArray = arrayOf(5, 2, 8, 1, 7)

    // Sorting the array of numbers and obtaining a new array
    val sortedNumbersArray = numbersArray.sorted()

    // Printing the original and sorted arrays
    println("Original Array\n[${numbersArray.joinToString(", ")}]")
    println("Sorted Elements in List\n[${sortedNumbersArray.joinToString(", ")}]")
}

Output

Original Array
[5, 2, 8, 1, 7]
Sorted Elements in List
[1, 2, 5, 7, 8]

2. Sorting an Array of Strings

In this example, we’ll use sorted() to obtain a new array with the elements of an array of strings sorted in lexicographical order.

Kotlin Program

fun main() {
    val wordsArray = arrayOf("banana", "kiwi", "apple", "mango")

    // Sorting the array of strings and obtaining the result in a list
    val sortedWordsArray = wordsArray.sorted()

    // Printing the original and sorted arrays
    println("Original Array\n[${wordsArray.joinToString(", ")}]")
    println("Sorted Elements in List\n[${sortedWordsArray.joinToString(", ")}]")
}

Output

Original Array
[banana, kiwi, apple, mango]
Sorted Elements in List
[apple, banana, kiwi, mango]

Summary

In this tutorial, we’ve covered the Array.sorted() function in Kotlin arrays, its syntax, and how to use it to obtain the elements sorted in ascending order in a List, without disturbing the original array.