Sort a mutable list in Kotlin
This article explores different ways to in-place sort a mutable list in the natural order in Kotlin while preserving the relative order of equal elements after sorting.
1. Using sort() function
The sort() function is the recommended way to in-place sort elements of the specified list. The sorting is done according to the natural ordering of its elements.
|
1 2 3 4 5 6 |
fun main() { val list = mutableListOf(4, 2, 6, 8, 7) list.sort() println(list) // [2, 4, 6, 7, 8] } |
To sort the list in reverse order, switch to the sortDescending() function.
|
1 2 3 4 5 6 |
fun main() { val list = mutableListOf(4, 2, 6, 8, 7) list.sortDescending() println(list) // [8, 7, 6, 4, 2] } |
2. Using sortWith() function
You can also sort the list according to the order specified by a comparator using the sortWith() function. This assumes that all elements of the list are mutually comparable by that comparator. The following example demonstrates this:
|
1 2 3 4 5 6 |
fun main() { val list = mutableListOf(4, 2, 6, 8, 7) list.sortWith(Comparator.naturalOrder()) println(list) // [2, 4, 6, 7, 8] } |
You can also implement your own comparator to sort a list, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
internal class CustomComparator<T : Comparable<T>> : Comparator<T> { override fun compare(x: T, y: T): Int { return x.compareTo(y) } } fun main() { val list = mutableListOf(4, 2, 6, 8, 7) list.sortWith(CustomComparator()) println(list) // [2, 4, 6, 7, 8] } |
This can be reduced to a single liner with lambda expressions:
|
1 2 3 4 5 6 |
fun main() { val list = mutableListOf(4, 2, 6, 8, 7) list.sortWith(Comparator{ x, y -> x.compareTo(y) }) println(list) // [2, 4, 6, 7, 8] } |
3. Using sortBy() function
The sortBy() function in-place sort elements of the list according to the natural sort order of the value returned by the specified selector function.
|
1 2 3 4 5 6 |
fun main() { val list = mutableListOf(4, 2, 6, 8, 7) list.sortBy { it } println(list) // [2, 4, 6, 7, 8] } |
To sort in descending order, pass the specified selector function to the sortByDescending() function:
|
1 2 3 4 5 6 |
fun main() { val list = mutableListOf(4, 2, 6, 8, 7) list.sortByDescending { it } println(list) // [5, 4, 3, 2, 1] } |
4. Using sortedWith() function
Finally, if you have an immutable list instance, you can create a new list of elements sorted according to natural order or order induced by the specified comparator. This can be done with sortedWith() function.
|
1 2 3 4 5 6 |
fun main() { val list = listOf(4, 2, 6, 8, 7) val sortedList = list.sortedWith(Comparator.naturalOrder()) // or, use compareBy { it } println(sortedList) // [2, 4, 6, 7, 8] } |
That’s all about sorting a mutable list in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)