Sort list in reverse order in Kotlin
This article explores different ways to sort a mutable list in reverse order in Kotlin. The sorting would be done in-place and is stable.
1. Using sortDescending() function
To sort the list in reverse order, you can use the native sortDescending() function.
|
1 2 3 4 5 6 |
fun main() { val list = mutableListOf(6, 4, 8, 7, 3) list.sortDescending() println(list) // [8, 7, 6, 4, 3] } |
2. Using sortByDescending() function
The sortByDescending() function sorts elements of the list descending according to the sort order of the value returned by the specified selector function.
|
1 2 3 4 5 6 |
fun main() { val list = mutableListOf(6, 4, 8, 7, 3) list.sortByDescending { it } println(list) // [8, 7, 6, 4, 3] } |
3. Using sortWith() function
You can also sort the list according to the order specified by a comparator using the sortWith() function.
|
1 2 3 4 5 6 |
fun main() { val list = mutableListOf(6, 4, 8, 7, 3) list.sortWith(Comparator.reverseOrder()) println(list) // [8, 7, 6, 4, 3] } |
You can also implement your own reverse comparator:
|
1 2 3 4 5 6 |
fun main() { val list = mutableListOf(6, 4, 8, 7, 3) list.sortWith(Comparator{ x, y -> y.compareTo(x) }) println(list) // [8, 7, 6, 4, 3] } |
4. Using sort() function
Another plausible way to get the reversed list is to sort it first in ascending order and then reverse the sorted list.
|
1 2 3 4 5 6 7 8 |
fun main() { val list = mutableListOf(6, 4, 8, 7, 3) list.sort() list.reverse() println(list) // [8, 7, 6, 4, 3] } |
5. Using sortedWith() function
Finally, if you have an immutable list instance, you can use the sortedWith() function to create a new list of elements sorted in reverse order using order induced by the specified comparator.
|
1 2 3 4 5 6 |
fun main() { val list = listOf(6, 4, 8, 7, 3) val sortedList = list.sortedWith(Comparator.reverseOrder()) println(sortedList) // [8, 7, 6, 4, 3] } |
That’s all about sorting a list in reverse order 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 :)