https://loizenai.com/kotlin-sort-sortby-sortwith-with-array-list-examples/

In the tutorial, I will introduce how to sort Kotlin Array using sorting functions: sort(), sortBy() with selector function, and sortWith() with a comparator.

  • Sorts the array in-place according to the natural order of its elements.

Examples:

val simpleArray = arrayOf(1, 4, 2, 20, 3, 40, 23, 12, 51)

// fun <T : Comparable> Array.sort()
simpleArray.sort()
simpleArray.forEach { print("${it} ") }
/*
-> 1 2 3 4 12 20 23 40 51
*/

  • Kotlin List sort() examples

Method signature:

public fun <T : Comparable> MutableList.sort(): Unit
-> Sorts elements in the list in-place according to their natural sort order.

Practice:

package com.loizenai.kotlin

fun main(args : Array){
val simpleList = mutableListOf(1, 4, 2, 20, 3, 40, 23, 12, 51)

simpleList.sort();
simpleList.forEach { print("${it} ") }
/*
-> 1 2 3 4 12 20 23 40 51
*/

}

All at: https://loizenai.com/kotlin-sort-sortby-sortwith-with-array-list-examples/

#kotlin #sort

Kotlin Sorting by: sort(), sortBy(), sortWith() with Array, List Examples
1.30 GEEK