Menu
Coddy logo textTech

Iterating Map Entries

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

A for loop can destructure each map entry into its key and value with for ((key, value) in map). Use the value for totals and the key for identity. Do not assume every map implementation has a sorted iteration order.

Inside main:

val stock = mapOf("a" to 3, "b" to 5)
var total = 0
for ((name, count) in stock) {
    total += count
}
println(total)

The two quantities contribute three and five.

Destructuring an entry provides its key first and value second.

challenge icon

Challenge

Medium

Complete stockTotal with parameters stock: Map<String, Int>. Use entry iteration to return the sum of all quantities. An empty map totals zero.

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 Int. 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 stockTotal(stock: Map<String, Int>): Int {
    // Write your solution here.
    return 0
}
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(stockTotal(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