Kotlin Array - sortBy() Function



The Kotlin array sortBy() function is used to sort an array of elements in place based on the natural sort order of the value returned by specified selector function.

The elements will be returned by this function will be in ascending 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 sortBy() function −

inline fun <T, R : Comparable<R>> Array<out T>.sortBy(
   crossinline selector: (T) -> R?)

Parameters

This function accepts selector as a parameters, which represents a function that defines the criteria for sorting.

Return value

This function does not returns any value. It only modifies the original array into ascending order.

Example 1

The following is a basic example to demonstrate the use of sortBy() function −

fun main(args: Array<String>){
   var arr = arrayOf<Int>(2, 4, 5, 6, 1)
        
   arr.sortBy({it})   
   println("Sorted array ")
   for (i in 0 until arr.size){
      println(arr.get(i))
   }   
}

Output

The above code generate following output −

Sorted array
1
2
4
5
6

Example 2

Now here, we create an array of string. We then use sortBy() function to sort the elements according to length of string −

fun main(args: Array<String>){
   var arr = arrayOf<String>("This", "is", "tutorialspoint", "India")
        
   arr.sortBy({it.length})   
   println("Sorted array:")
   for (i in 0 until arr.size){
      println(arr.get(i))
   }
}

Output

Following is the output −

Sorted array:
is
This
India
tutorialspoint

Example 3

The below example uses sortBy() function to sort the elements in alphabetical order −

fun main(args: Array<String>){
   var arr = arrayOf<Char>('t', 'u', 't', 'o', 'r', 'i', 'a', 'l', 's', 'p', 'o', 'i', 'n', 't')
   
   // sort the array
   arr.sortBy({it})   
   println("Sorted array:")
   println(arr.joinToString())
}

Output

Following is the output −

Sorted array:
a, i, i, l, n, o, o, p, r, s, t, t, t, u
kotlin_arrays.htm
Advertisements