Kotlin

Sorting Collections

admin by @admin ADMIN
Jun 13, 2026
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
`sortedBy { ... }` returns a sorted copy. `sortedWith(compareBy { ... })` chains tie-breakers cleanly. Avoid `sortBy` (in-place) on read-only lists.
Kotlin
Raw
data class User(val name: String, val age: Int, val signedUp: Long)

fun main() {
    val users = listOf(
        User("Bob",   25, 100L),
        User("Alice", 30, 200L),
        User("Cara",  25, 50L),
    )

    // Single field
    val byAge = users.sortedBy { it.age }
    val byAgeDesc = users.sortedByDescending { it.age }

    // Multiple fields — age asc, then name asc as tie-breaker
    val multi = users.sortedWith(compareBy({ it.age }, { it.name }))
    println(multi)

    // Mixed asc/desc — Comparator chain
    val complex = users.sortedWith(
        compareByDescending<User> { it.age }
            .thenBy                   { it.signedUp }
    )
    println(complex)

    // Pull the top N without fully sorting
    val newest3 = users.sortedByDescending { it.signedUp }.take(3)
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.