Ben Chuanlong Du's Blog

It is never too late to learn.

Sort a List in Kotlin

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]:
[2, 3, 5, 9]
In [2]:
val listPairs = listOf(Pair(5, 7), Pair(5, 3), Pair(1, 2), Pair(2, 3), Pair(1, 9))
listPairs
Out[2]:
[(5, 7), (5, 3), (1, 2), (2, 3), (1, 9)]
In [4]:
listPairs.sorted()
error: type parameter bound for T in fun <T : Comparable<T>> Iterable<T>.sorted(): List<T>
 is not satisfied: inferred type Pair<Int, Int> is not a subtype of Comparable<Pair<Int, Int>>
listPairs.sorted()
          ^

sortedBy

In [7]:
listPairs.sortedBy{ it.first }
Out[7]:
[(1, 2), (1, 9), (2, 3), (5, 7), (5, 3)]

sortedWith

In [5]:
listPairs.sortedWith(compareBy({it.first}, {it.second}))
Out[5]:
[(1, 2), (1, 9), (2, 3), (5, 3), (5, 7)]
In [ ]:

Comments