Sort list in kotlin

If you want to sort a list with kotlin, you can do that in just one step using sortedBy.

Sort a list with an ascending order with kotlin:

//let's define an unmutable list variable using val and listof
val list = listOf('a', 'c', 'b')

//sort the list by comparing every char
val sorted  = list.sortedBy { it }

Sort with a descending order you can simply use sortedByDescending:

val list = listOf('a', 'c', 'b')
val sorted  = list.sortedByDescending { it }

Sort a nested list

val list = listOf(mapOf("char" to "a"),mapOf("char" to "c"),mapOf("char" to "b"))
val sorted  = list.sortedBy { it["char"] }

Other articles