Kotlin Array - sorted() Function



The Kotlin array sorted() function is used to return a list of all elements in the array sorted according to their natural sort order.

This function creates a new sorted 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 sorted() function −

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

Parameters

This function does not accepts any parameters −

Return value

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

Example 1

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

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

Output

The above code generate following output −

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

Example 2

Now, we create an array of string. We then use sorted() function to sort the elements according to their natural sort order −

fun main(args: Array<String>){
   var arr = arrayOf<String>("This", "is", "tutorialspoint", "India")
        
   val list = arr.sorted()   
   println("sorted array list: $list")   
}

Output

Following is the output −

sorted array list: [India, This, is, tutorialspoint]

Example 3

The below example creates an array of type any. We then use sorted() function to see what will be the output −

fun main(args: Array<String>){
   var arr = arrayOf<Any>('t', 'u', 't', "tutorialspoint", "India", 5, 6, 1)
   
   // sort the array
   val list  = arr.sorted()   
   println("A list in ascending order: $list")
}

Output

The above code produce following error if an array of type any −

Unresolved reference. None of the following candidates is applicable because of a receiver type mismatch: fun <T : Comparable<T>> Array<out T>.sorted(): List<T>
kotlin_arrays.htm
Advertisements