Server Side Kotlin-15

Server Side Kotlin-15


2 min read

Custom orders

In Kotlin, achieving custom order for collections involves using comparators and specific functions. Here's a concise explanation:

Custom Sorting with Comparator: Kotlin provides the Comparator interface to define custom sorting orders. Use sortedWith() method along with a comparator to sort a collection based on custom criteria. Example: list.sortedWith(Comparator { o1, o2 -> customOrder.indexOf(o1) - customOrder.indexOf(o2) }) where customOrder is a predefined order .

Sorting Objects by Property: For sorting objects in a list based on a specific property, use sortedWith() with compareBy

For sorting in custom orders or sorting non-comparable objects, there are the functions sortedBy() and sortedByDescending() . Both takes a selector function which maps collection elements to Comparable values and sort the collection in natural order of that values.

i)-selector function()
ii)-which maps

iii)-map collection elements

iv)-to Comparable value
v)-and sort the collection
vi)-finally gives natural order of that value

val games = listOf("unity", "unreal", "godot", "bevy", "monogame", "supe rgame" )  

val sortedGames = games.sortedBy { it.length }

println("Sorted by length ascending: $sortedGames")
val sortedByLast = games.sortedByDescending { it.last() }

println("Sorted by the last letter descending: $sortedByLast")


Sorted by length ascending: [bevy, unity, godot, unreal, monogame, supe rgame]

Sorted by the last letter descending: [unity, bevy, godot, unreal, monogame, supe rgame

By calling sortedWith() and passing in Comparator, you can define custom order for the collection sorting. Sorting strings become linear.

val games = listOf("unity", "unreal", "godot", "bevy", "monogame", "supe rgame" )  
println("Sorted by length ascending: ${games.sortedWith(compareBy { it.length })}")


Sorted by length ascending: [bevy, unity, godot, unreal, monogame, supe rgame]

source: kotlin official web site