Library contents

Kotlin sortedWith and compareBy

sortedWith returns a new list in comparator order. Chain thenBy after a descending score comparator to break ties by name.

A simple example

sortedWith and compareBy

  1. Start with B and A with equal scores
  2. Do this Sort by score, then by name
  3. Result A, B
The second comparison resolves the tie in alphabetical order.

Syntax

Kotlin syntax
scores.sortedWith(compareByDescending<Player> { it.score }.thenBy { it.name })
Run this example in Kotlin

Save the program as Lesson.kt. Use Kotlin 2.2 on the JVM.

kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jar

Rank equal scores by a second key

A queue or leaderboard contains entries with equal primary scores. Specify how ties are handled so the final ordering is predictable and preserves arrival order when the task requires it.

First output lineAda, Bea, Cam
Lesson.kt
data class Player(val name: String, val score: Int)

fun main() {
    val players = listOf(Player("Bea", 8), Player("Cam", 5), Player("Ada", 8))
    val ranked = players.sortedWith(compareByDescending<Player> { it.score }.thenBy { it.name })
    println(ranked.joinToString { it.name })
    println(players.first().name)
}
Output
Ada, Bea, Cam
Bea

A secondary key makes the tie rule explicit. The source list keeps its input order, which allows the example to show both the ranking and the original first player.

Kotlin documentation for sortedWith and compareBy

Advertisements

Count packs on the delivery slip

A loading desk receives four item counts in sequence. The supervisor sorts the counts from smallest to largest. Which sequence goes on the summary sheet?

Given6 · 2 · 6 · 0
Worked result0 · 2 · 6 · 6

Review print quantities

A print room records four job quantities, including a cancelled job. The supervisor sorts the counts from smallest to largest. Which sequence goes on the summary sheet?

Given3 · 0 · 8 · 3
Worked result0 · 3 · 3 · 8