Kotlin Array - sortedArray() Function



The Kotlin array sortedArray() function creates a new sorted array without modifying the original and returns it with all elements sorted 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 sortedArray() function −

fun <T : Comparable<T>> Array<T>.sortedArray(): 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 ascending order.

Example 1

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

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

Output

The above code generate following output −

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

Example 2

Here is another example demonstrating the use of the sortedArray() 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 array
   val sortedNames = names.sortedArray()

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

Output

Following is the output −

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

Example 3

The below example creates a temperature array. We then use sortedArray() function to sort the temperatures is ascending order −

fun main(args: Array<String>) {
   val temperatures = arrayOf(98.6, 32.0, 212.0, 77.0, 68.0)

   // Get a new sorted array
   val sortedTemperatures = temperatures.sortedArray()

   println("Original temperatures: ${temperatures.joinToString(", ")}")
   println("Sorted temperatures: ${sortedTemperatures.joinToString(", ")}")
}

Output

Following is the output −

Original temperatures: 98.6, 32.0, 212.0, 77.0, 68.0
Sorted temperatures: 32.0, 68.0, 77.0, 98.6, 212.0
kotlin_arrays.htm
Advertisements