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.

Download Code

 
To sort the list in reverse order, switch to the sortDescending() function.

Download Code

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:

Download Code

 
You can also implement your own comparator to sort a list, as shown below:

Download Code

 
This can be reduced to a single liner with lambda expressions:

Download Code

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.

Download Code

 
To sort in descending order, pass the specified selector function to the sortByDescending() function:

Download Code

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.

Download Code

That’s all about sorting a mutable list in Kotlin.