https://grokonez.com/kotlin/kotlin-array-sort-sortby-sortwith
Kotlin Array sort(), sortBy(), sortWith()
In the tutorial, JavaSampleApproach will guide how to sort Kotlin Array by sort()
, sortBy()
with selector function, and sortWith()
with a comparator.
fun <T : Comparable<T>> Array<out T>.sort()
-> Sorts the array in-place according to the natural order of its elements.
Practice:
val simpleArray = arrayOf(1, 4, 2, 20, 3, 40, 23, 12, 51)
// fun <T : Comparable<T>> Array<out T>.sort()
simpleArray.sort()
simpleArray.forEach { print("${it} ") }
/*
-> 1 2 3 4 12 20 23 40 51
*/
For descending sorting, we can use sortDescending()
. Method signature:
public fun <T : Comparable<T>> Array<out T>.sortDescending(): Unit
Practice:
More at:
https://grokonez.com/kotlin/kotlin-array-sort-sortby-sortwith
Kotlin Array sort(), sortBy(), sortWith()
#kotlin #array #sort #sortby #sortwith