Kotlin Array - sortedWith() Function



The Kotlin array sortedWith() function is used to return a list containing elements of an array in the sorted order according to the specified comparator function.

A comparator is a function that returns 1, -1, or 0 depending on the comparison of the two variables passed to the 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 sortedWith() function −

fun <T> Array<out T>.sortedWith(
   comparator: Comparator<in T>
): List<T>

Parameters

This function accepts a comparator as a parameter.

Return value

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

Example 1

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

fun main(args: Array<String>){
   val arr = arrayOf<Int>(5, 3, 6, 7, 4)
   var res = arr.sortedWith(Comparator<Int>{ a, b ->
      when {
         a > b -> 1
         a < b -> -1
         else -> 0
      }
   })
   println("Sorted array: $res")
}

Output

The above code generate following output −

Sorted array: [3, 4, 5, 6, 7]

Example 2

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

fun main(args: Array<String>){
   val arr = arrayOf<String>("Daisy", "Rahul", "Ram", "Prajwalani")
   var res = arr.sortedWith(Comparator<String>{ a, b ->
      when {
         a > b -> 1
         a < b -> -1
         else -> 0
      }
   })
   println("Sorted array: $res")
}

Output

Following is the output −

Sorted array: [Daisy, Prajwalani, Rahul, Ram]

Example 3

The below example creates a comparator to sort elements in descending order. We then use sortedWith() function to sort elements of an array according to this comparator −

fun main(args: Array<String>) {
   val numbers = arrayOf(42, 7, 23, 89, 5, 34)

   // Display the original array
   println("Original array: ${numbers.joinToString(", ")}")

   // create a custom comparator to sort the array in descending order
   val descendingComparator = Comparator<Int> { a, b -> when {
      a < b -> 1
      a > b -> -1
      else -> 0 }       
   }

   // Sort the array using the custom comparator
   val sortedNumbers = numbers.sortedWith(descendingComparator)
    
   // Display the sorted array
   println("Sorted array with comparator: ${sortedNumbers.joinToString(", ")}")
}

Output

The above code produce following output −

Original array: 42, 7, 23, 89, 5, 34
Sorted array with comparator: 89, 42, 34, 23, 7, 5
kotlin_arrays.htm
Advertisements