Kotlin Collections Ordering

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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))
}

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Here we used length to compare rather than prescribed lexicographial 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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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")

chevron_right


Using sortedWith(), this can be written as:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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")
println(numbers.shuffled())

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.