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
- Start with B and A with equal scores
- Do this Sort by score, then by name
- Result A, B
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.
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)
}
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
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?
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?