Menu
Coddy logo textTech

Keys and Values

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

keys provides the distinct keys and values provides the values, which may repeat. Convert or sort the keys when a stable report order is needed. Here, sorted string keys use the case-sensitive ordering taught for lists.

Inside main:

val scores = mapOf("Bo" to 7, "Ada" to 7)
println(scores.keys.sorted())

Sorting the keys gives Ada before Bo, independently of insertion order.

Sort keys explicitly when you need predictable alphabetical output.

challenge icon

Challenge

Medium

Complete sortedNames with parameters stock: Map<String, Int>. Return the map's keys as a sorted list. All keys are lowercase ASCII words.

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 sortedNames(stock: Map<String, Int>): List<String> {
    // Write your solution here.
    return emptyList()
}
fun main() {
    val stockCount = readln().toInt()
    val stock = mutableMapOf<String, Int>()
    for (i0 in 0 until stockCount) {
        val stockKey = readln()
        val stockValue = readln().toInt()
        stock[stockKey] = stockValue
    }
    println(sortedNames(stock))
}
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