The ordering of elements matters in certain collection types. For example, two lists having same elements are not the same if their elements have been ordered differently.
In Kotlin, the order of the objects is defined in several ways.
First, we have natural order and it is defined for Comparable interface inheritors. Natural order is used as a default order to sort them, when no other order is specified.
Most built in types are comparable, such as:
- Numeric types, which use the traditional numerical order like 2 is greater than 1 ; -2.5 is greater than -3.5 and so on.
- Char and String types, which use the lexicographical order: p is greater than m.
To define a natural order for a user-defined type, make it an inheritor of Comparable interface. And this is done through the implementation of compareTo() method. compareTo() must take another object of the same type as an argument and return an integer to show which of the objects is greater.
- Positive value indicates that receiver object is greater.
- Negative value indicates that the receiver is less than the argument.
- Zero indicates equality of both.
Below is an example for a class that is used for ordering versions that consists of the major and the minor part.
class Version(val maj: Int, val min: Int): Comparable<Version> {
override fun compareTo(other: Version): Int {
if (this.maj != other.maj) {
return this.maj - other.maj
} else if (this.min != other.min) {
return this.min - other.min
} else return 0
}
}
fun main() {
println(Version(1, 2) > Version(1, 3))
println(Version(2, 0) > Version(1, 5))
}
Custom order allows us to sort instances of any type in a way that we’d like to. You can define an order other than natural for comparable type or you can define an order for non-comparable objects. To define a custom order for a type, you need to create a Comparator for it. Comparator includes the compare() method which takes two instances of a class and returns the result of the comparision in the form of an integer. The result is interpreted the same way as the result of above compareTo() method.
fun main() {
val lenCompare = Comparator { str1: String, str2: String -> str1.length - str2.length }
println(listOf("zzzz", "yyy", "x").sortedWith(lenCompare))
}
lenCompare allows you to arrange strings by their length instead of their lexicographical order.
To be more concise, we can define a Comparator by the use compareBy() method from the standard library. compareBy() takes a lambda method which gives a Comparable value from an instance and defines the custom orders of the produced values as the natural order. Using compareBy(), the length comparator from the above code would look like this:
fun main() {
println(listOf("zzzz", "yyy", "x").sortedWith(compareBy { it.length }))
}
The collection package in Kotlin provides functions to help sort collections in natural, custom and random orders.
Natural Order :
The basic methods sorted() and sortedDescending() return elements of the collection sorted in ascending and descending sequence respectively according to their natural order. These methods apply to collection of Comparable elements.
fun main() {
val nums = listOf("one", "two", "three", "four")
println("Ascending: ${nums.sorted()}")
println("Descending: ${nums.sortedDescending()}")
}
Custom Order :
For sorting in custom orders or sorting of non-comparable objects, we have methods like sortedBy() and sortedByDescending(). They take a selector method that maps the collection elements to Comparable values and sort the collection in natural order of the values.
fun main() {
val nums = listOf("one", "two", "three", "four")
val sortedNums = nums.sortedBy { it.length }
println("Sorting by length ascending: $sortedNums")
val sortedLast = nums.sortedByDescending { it.last() }
println("Sorting by last letter descending: $sortedLast")
}
We can also provide our own Comparator to define a custom order for the collection sorting. To do this, we call the sortedWith() method passing in our Comparator. With this method, sorting the strings by their length would look like this:
fun main() {
val nums = listOf("one", "two", "three", "four")
println("Sorted by length ascending: ${nums.sortedWith(compareBy { it.length })}")
}
Reverse order :
You can fetch the string in reversed order with the use of reversed() method.
fun main() {
val nums = listOf("one", "two", "three", "four")
println(nums.reversed())
}
The method returns you a new collection with copies of the elements. So, if you make any variations in the original collection, it would not effect the priorly obtained results from reversed().
Another method – asReversed() – returns the reversed view of same collection, so it is more preferable and lightweight to use if no variations are to be made in the original list.

fun main() {
val nums = listOf("one", "two", "three", "four")
val reversedNums = nums.asReversed()
println(reversedNums)
}
If the original list is mutated, the variations made to it do reflect in its reversed view and vice-versa.
fun main() {
val nums = mutableListOf("one", "two", "three", "four")
val reversedNums = nums.asReversed()
println(reversedNums)
nums.add("five")
println(reversedNums)
}
However, if we are unsure about the lists’ mutability, reversed() is preferred since its result is a copy that would have no effect of changes made in the original list in the future.
Random Order :
And here we come to a method that returns a new List that consists of the collection elements in a random order – shuffled(). It can be called without arguments or with a Random object.
fun main() {
val nums = listOf("one", "two", "three", "four")
println(nums.shuffled())
}