Menu
Coddy logo textTech

Combining Comparisons

Part of the Logic & Flow section of Coddy's Kotlin journey. Lesson 37 of 63.

Use sortedWith to provide a comparator. compareBy<String> { it.length } compares word lengths; chaining .thenBy { it } compares the word itself when lengths tie. Later comparison keys are used only when all earlier keys tie.

Inside main:

val order = compareBy<String> { it.length }.thenBy { it }
println(listOf("bb", "a", "aa").sortedWith(order))

Length puts a first; alphabetical comparison breaks the two-character tie.

thenBy breaks ties without replacing the earlier comparison key.

challenge icon

Challenge

Medium

Complete wordOrder with parameters words: List<String>. Sort lowercase ASCII words by increasing length, then alphabetically for ties.

Unless stricter bounds are stated above, collections contain at most 100 elements at each level, and integer arguments and integer collection values are between -1000 and 1000. Text supplied for parsing can include invalid or out-of-range representations as described.

Return a value of type List<String>. Keep the supplied input/output code. It reads scalar arguments one per line; a list starts with its count followed by its elements, and a map starts with its entry count followed by each key and value. Nested lists repeat the count-and-elements format for each row. The supplied main prints the return value followed by one newline. Lists use Kotlin's standard bracketed format; print no additional labels.

Try it yourself

fun wordOrder(words: List<String>): List<String> {
    // Write your solution here.
    return emptyList()
}
fun main() {
    val wordsCount = readln().toInt()
    val words = mutableListOf<String>()
    for (i0 in 0 until wordsCount) {
        val wordsItem = readLine().orEmpty()
        words.add(wordsItem)
    }
    println(wordOrder(words))
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Kotlin playground