CodeGym /Courses /Kotlin SELF /Iterating over a Map: keys, values, entries, Map.Entry, a...

Iterating over a Map: keys, values, entries, Map.Entry, and destructuring (k, v)

Kotlin SELF
Level 20, Lesson 2
Available

1. A Map is not iterated like a list: keys instead of indices

If a List is like a numbered to-do list, a Map is more like a phone book: by “name” (key) we look up the “number” (value). That’s why trying to “walk through a map by indices” sounds just as odd as asking “give me the third contact” without specifying the order. In Kotlin, Map<K, V> stores “key → value” pairs; keys are unique, and iteration order should not be the basis of your logic.

The most important idea: Map is not a “list of pairs”, but a structure where access to data goes through a key. And it’s exactly from this idea that the correct iteration approaches follow.

Reminder: how a Map is created and what Pair is

Before iterating, you need something to iterate over. Usually we create a map via mapOf(...) or mutableMapOf(...), passing in Pair<K, V> values. Most often, pairs are created via the infix function to, which looks like a small arrow “key to value”.

For example:

fun main() {
    val prices = mapOf(
        "coffee" to 250,
        "tea" to 120
    )

    println(prices) // {coffee=250, tea=120}
}

This is just a starting point. Next we’ll iterate over such maps in different ways—depending on the task.

Nuance: map[key] returns V?

When you read a value by key, it’s as if you’re asking the map: “do you have such a key?”. If the key is missing, the map cannot “guess” the value, so null is returned. That’s exactly why the expression map[key] has type V?, even if V itself is not nullable.

In practice, it looks like this:

fun main() {
    val ages = mapOf("Ann" to 20, "Bob" to 31)

    val annAge = ages["Ann"]
    val kateAge = ages["Kate"]

    println(annAge)  // 20
    println(kateAge) // null
}

And this is where many beginners fall into a trap: they start iterating over keys and then pull the value via map[key], and suddenly run into null. In this lecture we’ll cover iteration techniques that make such code simpler, safer, and more readable.

2. Map views: keys, values, entries

When you iterate over a Map, you almost always want one of three things: iterate over keys, iterate over values, or iterate over the whole pairs. Kotlin makes this explicit: a map has keys, values, and entries. These are not three different maps—they are “windows” (views) into the same structure, just with different perspectives on the data.

Let’s lock this in with a small table—it will come in handy every time your hand reaches to “iterate over a Map like a List”.

What you need to do What to iterate over What you get in the loop
Only keys are needed
map.keys
K
Only values are needed
map.values
V
Key and value are needed together
map.entries
Map.Entry<K, V>
Key and value are needed together (short syntax)
for ((k, v) in map)
(K, V)

Iterating over keys: for (k in map.keys)

Sometimes the logic doesn’t care about the value at all; the important thing is the set of keys. For example, you want to print the list of categories in our learning console app (a hypothetical “expense tracker”) or check whether the category "food" exists at all.

fun main() {
    val totalsByCategory = mapOf(
        "food" to 1200,
        "transport" to 450
    )

    for (category in totalsByCategory.keys) {
        println(category)
    }
    // food
    // transport
}

The plus of this approach is that it honestly tells the reader: “I’m working with keys”. The downside is that if you later still need values, you’ll either add a second pass or start pulling map[category], and you’re back to V?.

Iterating over values: for (v in map.values)

If you care only about the values, you can iterate over values. For example, you want to calculate the total sum across all categories (for now without advanced collection operations—just a plain loop).

fun main() {
    val totalsByCategory = mapOf(
        "food" to 1200,
        "transport" to 450
    )

    var sum = 0
    for (value in totalsByCategory.values) {
        sum += value
    }

    println("Total = $sum") // Total = 1650
}

This approach is good when keys truly aren’t needed. And yes, this happens more often than it seems: keys are often needed “for pretty output”, but not for computations.

Iterating over pairs: for (entry in map.entries)

If you need both the key and the value, the most straightforward way is to iterate over entries. Each element of entries is a Map.Entry<K, V>, i.e., a pair object with fields key and value.

fun main() {
    val totalsByCategory = mapOf(
        "food" to 1200,
        "transport" to 450
    )

    for (entry in totalsByCategory.entries) {
        println("${entry.key} -> ${entry.value}")
    }
    // food -> 1200
    // transport -> 450
}

This option typically beats “iterating over keys + map[key]”, because you don’t perform a repeated lookup by key and you don’t have to deal with V?.

What Map.Entry<K, V> is and how it differs from Pair

Map.Entry is a “wrapper” for one pair inside a Map. It’s important to understand: Entry is not necessarily a Pair. It’s a separate type that reflects the meaning of a “map element”. It provides access to entry.key and entry.value, and most importantly, it allows Kotlin and the standard library to build predictable APIs around Map.

To reinforce this, here’s a small “who is made of what” diagram:

flowchart TD
    M["Map⟨K, V⟩"] --> KEYS["keys: Set⟨K⟩"]
    M --> VALUES["values: Collection⟨V⟩"]
    M --> ENTRIES["entries: Set⟨Entry⟨K, V⟩⟩"]
    ENTRIES --> E["Entry⟨K, V⟩"]
    E --> K["key: K"]
    E --> V["value: V"]

Practical takeaway: when you iterate over entries, you almost never need to go back to the map by key. You’re already standing on the pair, holding it with both hands, and can work directly.

3. Destructuring and choosing an iteration style

Destructuring: for ((k, v) in map)

Sometimes writing entry.key / entry.value feels a bit verbose. Kotlin allows you to “unpack” the pair into two variables directly in a for. This is called destructuring, and in the case of a Map it looks very natural: for ((k, v) in map).

Important: when you write for ((k, v) in map), you are iterating over pairs—just with more compact syntax.

fun main() {
    val totalsByCategory = mapOf(
        "food" to 1200,
        "transport" to 450
    )

    for ((category, total) in totalsByCategory) {
        println("$category: $total")
    }
    // food: 1200
    // transport: 450
}

This option is usually the most readable if you need both parts of the pair and you don’t do anything overly complex inside the loop. It also nudges you to give variables good names: category, total, name, age.

How to choose an iteration style

A rule that saves a lot of nerves: if you need only one part of the data, iterate only that (keys or values). If you need both, iterate over pairs (entries or destructuring). This makes the code straightforward and errors less likely.

Let’s compare two approaches on the same example—print category -> total.

Approach “by keys, and I’ll fetch the value later”:

fun main() {
    val totalsByCategory = mapOf("food" to 1200, "transport" to 450)

    for (category in totalsByCategory.keys) {
        val total = totalsByCategory[category]
        println("$category -> $total")
    }
    // food -> 1200
    // transport -> 450
}

It works, but here total has type Int?, which is a bit annoying.

Approach “by pairs”:

fun main() {
    val totalsByCategory = mapOf("food" to 1200, "transport" to 450)

    for ((category, total) in totalsByCategory) {
        println("$category -> $total")
    }
    // food -> 1200
    // transport -> 450
}

Here total is a regular Int, which is exactly what we want in 99% of cases.

4. Practice: report by category

Let’s add this topic to the very app we’re building throughout the course: a console expense tracker. We are not using OOP yet, so expenses can be stored as a simple Triple<String, String, Int>: (category, title, amount). Yes, it’s not ideal, but our task right now is to practice collections and iteration, not domain model design.

Below is a small piece of logic: we already have a list of expenses and want to build a Map of “category → total”, and then print a nice report. We won’t use advanced collection operations (that will come later); we’ll do it with an honest loop.

fun buildTotalsByCategory(expenses: List<Triple<String, String, Int>>): Map<String, Int> {
    val totals = mutableMapOf<String, Int>()

    for (e in expenses) {
        val category = e.first
        val amount = e.third

        val oldTotal = totals[category] ?: 0
        totals[category] = oldTotal + amount
    }

    return totals
}

Pay attention to totals[category] ?: 0. We read from a Map, get an Int?, and if it’s null (the category doesn’t exist yet), we treat the old total as zero. This is a classic pattern for Map, and it fits well with the fact that key access returns V?.

Now—the report printing function. And this is where iterating over a Map via destructuring will really help:

fun printTotalsReport(totalsByCategory: Map<String, Int>) {
    println("Totals by category:")

    for ((category, total) in totalsByCategory) {
        println("- $category: $total")
    }
}

Now let’s assemble this into a micro-scenario:

fun main() {
    val expenses = mutableListOf(
        Triple("food", "coffee", 250),
        Triple("food", "sandwich", 350),
        Triple("transport", "metro", 70)
    )

    val totals = buildTotalsByCategory(expenses)
    printTotalsReport(totals)

    // Totals by category:
    // - food: 600
    // - transport: 70
}

Nuance: it’s better not to turn Map iteration order into “part of the logic”

When you print a report, sometimes you want categories to go “in the order they were added”. In practice, this may look as if a Map has an order. And sometimes it really will be preserved, because the standard MutableMap implementation in Kotlin is LinkedHashMap, which preserves insertion order during iteration. But another implementation (HashMap) does not promise anything about order.

Practical rule: don’t make your program’s correctness depend on the iteration order of a Map. If order matters as part of the requirements, that’s a separate task and should be solved explicitly—not with “well, it seems to print nicely”.

7. Common mistakes when iterating over a Map

Mistake #1: trying to iterate over a Map by indices, “like a list”.
Sometimes your brain, by habit, looks for map[0], map[1], map.indices. But a map has no indices: it’s not about positions, it’s about correspondences “key → value”. If you need a “row number” when printing a report, you can keep numbering with a separate counter, but the iteration itself still should go via keys/values/entries or destructuring.

Mistake #2: iterating over keys and fetching values via map[key], then getting annoyed by V?.
This is not a “Kotlin whim”, it’s an honest model: the key may be missing. If you need pairs—iterate over pairs. for ((k, v) in map) or for (entry in map.entries) usually removes the problem completely, because in the loop you already have both key and value without a second lookup.

Mistake #3: writing for (k in map.keys) println(map[k]!!).
This is a dangerous habit. Yes, in this specific situation “the keys are from the same map”, so map[k] really isn’t null. But you get used to solving null questions with !!, and later that habit will backfire somewhere else—where keys come from the outside (for example, from user input). It’s better to choose an iteration style right away that doesn’t force you to prove the obvious to the compiler.

Mistake #4: iterating over values, and then suddenly needing to “figure out which key this value belongs to”.
This happens when you started with “I only need the totals”, and then you want to print “category: total”. If keys are actually needed, then you should iterate over pairs. values are useful, but only when you’re sure keys do not participate in the logic at all.

Mistake #5: building program meaning on the Map iteration order.
Today everything prints “as it should”, tomorrow you changed the map implementation or data starts arriving in a different order—and the output “breaks”. A correct program should not depend on a random order. If order matters, it should be designed separately, not hoped for with “well, it works for me right now”.

1
Task
Kotlin SELF, level 20, lesson 2
Locked
Console Menu
Console Menu
1
Task
Kotlin SELF, level 20, lesson 2
Locked
Learning summary
Learning summary
1
Task
Kotlin SELF, level 20, lesson 2
Locked
City report
City report
1
Task
Kotlin SELF, level 20, lesson 2
Locked
Friends' Contacts
Friends' Contacts
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION