sorted¶
If elements in a List implements the Comparable interface,
you can call the method sorted
to return a sorted List (in nature order).
Note: Pair in Kotin does not implement the Comparable interface!!!
In [7]:
listOf(5, 9, 3, 2).sorted()
Out[7]:
In [2]:
val listPairs = listOf(Pair(5, 7), Pair(5, 3), Pair(1, 2), Pair(2, 3), Pair(1, 9))
listPairs
Out[2]:
In [4]:
listPairs.sorted()
sortedBy¶
In [7]:
listPairs.sortedBy{ it.first }
Out[7]:
sortedWith¶
In [5]:
listPairs.sortedWith(compareBy({it.first}, {it.second}))
Out[5]:
References¶
https://stackoverflow.com/questions/33640864/how-to-sort-based-on-compare-multiple-values-in-kotlin
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/sort.html
https://www.baeldung.com/kotlin-sort
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.comparisons/natural-order.html
In [ ]: