Open In App

Kotlin Collections Ordering

Last Updated : 14 Sep, 2021
Like Article

There are certain collections where the order of the elements is important. If you take lists, two lists are never equal if they are ordered differently inspite of having same elements.In Kotlin, there are different ways of ordering the elements. 
Most built-in types are comparable: 
-Numeric types follow the numerical order: 1 is greater than 0; -2.8f is greater than -6f, an so on. 
-Char and String use the lexicographical order: p is greater than a; sky is greater than air. 
For user-defined type, there are different types of orders defined in Kotlin.They can be described as follows:

Natural Order

It is defined for all those types which are inherited from Comparable interface.To define this order for any type, it should be made an inheritor of Comparable.This can be done using compareTo() function which takes other element of same type and returns which is greater in the form of an integer value.Based on this integer values we can determine which object is greater. 
-Positive value indicates receiver object is greater 
-Negative value shows receiver < argument 
-Zero implies both objects are equal. 
Below is a class that can be used for ordering items that consist of the big and the small part.


class Items(val big: Int, val small: Int): Comparable {
    override fun compareTo(other: Items): Int {
        if (this.big != other.big) {
            return this.big - other.big
        } else if (this.small != other.small) {
            return this.small - other.small
        } else return 0
?fun main() {   
    println(Items(1, 2) > Items(1, 3))
    println(Items(2, 0) > Items(1, 5))

Basic functions are sorted() and sortedDescending().They give the result in form of collection of objects sorted into Ascending and Descending orders.These can be applied to collections of Comparable events

Custom Ordering

They let you order instances in any type you want.This is especially useful for defining order for objects which are generally non comparable. 
To create a custom order, we create a Comparator containing the compare() function. It takes two instances and compares them giving integer value as output. This result is also similar to the above method.


val lengthComparator = Comparator { str1: String,
                       str2: String -> str1.length - str2.length }
println(listOf("aaa", "bb", "c").sortedWith(lengthComparator))

Here we used length to compare rather than prescribed lexicographical order. 
Comparator can also be defined using compareBy() from standard library.This function takes a lambda function which produces a value which is used to compare and define the custom order as the natural order of produced values. 
Using compareBy(),

println(listOf("aaa", "bb", "c").sortedWith(compareBy { it.length }))

Basic functions are sortedBy() and sortedByDescending().They map the collection elements to Comparable values using a defined selector function and sort the collection in natural order of values.


val numbers = listOf("one", "two", "three", "four")
val sortedNumbers = numbers.sortedBy { it.length }
println("Sorted by length ascending: $sortedNumbers")
val sortedByLast = numbers.sortedByDescending { it.last() }
println("Sorted by the last letter descending: $sortedByLast")

Using sortedWith(), this can be written as: 


val numbers = listOf("one", "two", "three", "four")
println("Sorted by length ascending: ${numbers.sortedWith(compareBy { it.length }

Random order

The function which gives a new List containing the collection elements in a random order using shuffled(). No arguments or with a Random object required.

val numbers = listOf("one", "two", "three", "four")


Reverse Order

The elements can be reversed using reversed(). It returns a new collection where the reverse of original is given. The original will not be changed since this result is basically a copy.Another version is asReversed() which provides reversed view instead of copy and hence is lightweight. 


val numbers = listOf("one", "two", "three", "four")
val numbers = listOf("one", "two", "three", "four")
val reversedNumbers = numbers.asReversed()

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads