Kotlin Array - sortedBy() Function



The Kotlin array sortedBy() function is used to return a list containing all elements sorted in ascending order according to the natural sort order of the value returned by specified selector function.

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 sortedBy() function −

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

Parameters

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

Return value

This function returns a list containing all elements in ascending order.

Example 1

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

fun main(args: Array<String>){
   var arr = arrayOf<Int>(2, 4, 5, 6, 1)        
   val list = arr.sortedBy({it})   
   println("Sorted list: $list")
}

Output

The above code generate following output −

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

Example 2

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

fun main(args: Array<String>){
   var arr = arrayOf<String>("This", "is", "tutorialspoint", "India")
        
   val list = arr.sortedBy({it.length})   
   println("Sorted list:")
   println(list)
}

Output

Following is the output −

Sorted list:
[is, This, India, tutorialspoint]

Example 3

The below example creates a person class that takes the person's age as argument. We then use sortedBy() function to sort the age of the person in ascending order −

class Person(var age: Int) {
   override fun toString(): String {
      return "(age=$age)"
   }
}
fun main(args: Array<String>) {
   val p1 = Person(24)
   val p2 = Person(25)
   val p3 = Person(26)
   val listOfage = arrayOf(p1, p2, p3)
   val sorted_age_list = listOfage.sortedBy { it.age }
   println("List of person ages:")
   println(sorted_age_list)
}

Output

Following is the output −

List of person ages:
[(age=24), (age=25), (age=26)]
kotlin_arrays.htm
Advertisements