1. Why you need a Map and how to read Map<K, V>
When you’re just getting used to collections, it’s very easy to think like this: “I need a list, so List.” And that’s true… until you run into a task where the key to the data is not a position (0, 1, 2…), but some meaningful label: a product name, a team, a login, a category, an ID.
Map<K, V> (a map, a dictionary) stores pairs “key → value”. Keys are unique: two identical keys cannot live in the same map. But values can repeat as much as you want: for example, products can have the same price, while the keys (product names) are still different.
Key point: Map in Kotlin is a separate “world”; it does not inherit from Collection, even though it belongs to collections as a standard-library data type.
How to read the type Map<K, V> without being scared of angle brackets
When you see Map<String, Int>, your brain may first pretend it’s busy: “let’s do it later, I’m not ready.” That’s normal. What matters here is learning to read the type out loud like a sentence. Map<K, V> is read as “a map from keys of type K to values of type V.” So Map<String, Int> means “keys are strings, values are integers.”
In real life, this could be “product name → price”, “category → total spending”, “word → how many times it occurred”. No magic: angle brackets just pin down what exactly we put in and take out.
Let’s look at a “pocket price list”:
fun main() {
val prices: Map<String, Int> = mapOf(
"tea" to 90,
"coffee" to 150
)
println(prices) // {tea=90, coffee=150}
}
Notice to. It’s a convenient way to create a “key-value” pair so that mapOf(...) reads like “a list of correspondences”.
2. Reading from a Map: why you get V? and how to live with it
If you’re used to List, you expect the logic “give me an element by index — and you get an element.” But in a Map, a key can be missing. And Kotlin does a very sane thing: instead of “blowing up” with an error, a lookup by key returns null if the key is not found.
That’s exactly why the expression map[key] has type V?, even if V itself is not nullable. This is one of the most important details, and it will keep coming up as you write any programs involving Map.
fun main() {
val prices = mapOf("tea" to 90, "coffee" to 150)
val a: Int? = prices["tea"]
val b: Int? = prices["milk"]
println(a) // 90
println(b) // null
}
There’s no “error” here. milk is simply absent — and that’s a normal situation, not a catastrophe.
Elvis ?: when reading: “if the key is missing — use a default value”
Once you accept the reality of V?, the next question is: “Okay, what if null doesn’t work for me?” In simple scenarios, the Elvis operator ?: works best: “if the left side is null, take the right side.”
This is especially handy for numbers when you have a “natural zero.” For example, if there is no price — treat the price as 0 (or “unknown”, but that’s a different design).
fun main() {
val prices = mapOf("tea" to 90, "coffee" to 150)
val milkPrice = prices["milk"] ?: 0
val teaPrice = prices["tea"] ?: 0
println(milkPrice) // 0
println(teaPrice) // 90
}
Here we explicitly choose a policy: “no key → 0”. The important part is that Kotlin forces you to make a decision, rather than pretend the key “definitely exists.”
Checking for a key: key in map as a readable style
Sometimes a default value doesn’t fit. For example, if a team doesn’t exist, you want to print an error message rather than “quietly” continue. Then we first check whether the key is in the map.
Kotlin lets you write this very readably: if (key in map). Semantically, it’s exactly “if the key belongs to the set of keys of the map.”
fun main() {
val prices = mapOf("tea" to 90, "coffee" to 150)
val item = "tea"
if (item in prices) {
println("Price: ${prices[item]}") // Price: 90
} else {
println("No such item") // (won't run)
}
}
Here prices[item] still returns Int?, but in this code shape you are usually already confident the key exists. A bit later in the course you’ll learn to do this even more neatly, but at the current stage this is enough: a check + a clear behavior branch.
3. MutableMap: writing, updating, and deleting
So far we used mapOf(...), i.e., a read-only Map. Its job is “store and let you read.” But if you need to change data while the program runs, use MutableMap.
In Kotlin, this split is the same as with List: a read-only type (Map) and a mutable type (MutableMap). At the same time, MutableMap supports write operations: you can add new pairs and update existing values.
One form for both “add” and “update”
The nicest thing is that writing looks the same for both “add” and “update”:
fun main() {
val stock = mutableMapOf<String, Int>()
stock["apple"] = 3
stock["apple"] = 4
stock["banana"] = 1
println(stock) // {apple=4, banana=1}
}
That is, the [] operator for MutableMap works in both directions: reading map[key] and writing map[key] = value. This is one reason maps in Kotlin feel like an “honest dictionary” rather than something clunky.
A small practical detail: the default standard implementation of MutableMap is LinkedHashMap, and when iterating it preserves insertion order. Today we won’t iterate the map (that’s the topic for the next day), but it’s useful to understand why with println(map) you often see “pairs in the expected order.”
Deleting by key: remove(key) and “what exactly got returned”
Deletion in MutableMap is usually done like this: remove(key). And here Kotlin again behaves “like an adult”: the method returns the value that was removed, or null if there was no such key.
This is convenient because with a single expression you can tell whether there was anything to remove.
fun main() {
val stock = mutableMapOf("apple" to 4, "banana" to 1)
val removed: Int? = stock.remove("banana")
val removedAgain: Int? = stock.remove("banana")
println(removed) // 1
println(removedAgain) // null
println(stock) // {apple=4}
}
Same philosophy again: “missing key” is a normal state of the world, not an exception.
Mini table: what the basic Map operations return
Sometimes it’s easier to see the “contract” of the operations once than to read the explanation ten times. In this section we’ll carefully pin down what types are returned so you stop being surprised by ? in unexpected places (this surprise is one of the most common sources of frustration for beginners).
| Operation | Example | What is returned | Why |
|---|---|---|---|
| Read by key | |
|
the key may be missing |
| Key check | |
|
just the presence fact |
| Write/update | |
|
it’s an action, not a “value” |
| Delete | |
|
you can learn what was removed |
This table is not “something to memorize,” but “something to get used to.” After a couple of exercises, your brain will start automatically expecting nullable when reading from a map.
4. The “counter” pattern: increase the value by key
Now comes one of the most practical techniques. You’ll see it everywhere: statistics, counts, frequencies, “how many times a user did X,” “how much spending is in category Y.” And it’s done literally in one line.
The problem sounds like this: “I want to increase the counter for a key. But if the key is missing, the counter should be treated as 0.”
Solution: (map[key] ?: 0) + 1, and then write it back.
fun main() {
val counts = mutableMapOf<String, Int>()
val word = "kotlin"
counts[word] = (counts[word] ?: 0) + 1
counts[word] = (counts[word] ?: 0) + 1
println(counts) // {kotlin=2}
}
It looks almost too simple — but it’s exactly the kind of simplicity people love Kotlin for: everything is honest, and null is handled explicitly.
Example: “word counter” without functional chains
It’s very tempting to already write nicely using map/filter/groupBy, but we agreed: today, no “collection operations,” only basic tools. So we’ll make the clearest possible version: read a line, split into words, normalize case, and count frequencies.
We’ll count words separated by spaces. This is not a perfect text parser (punctuation will stay in the words), but for practicing Map it’s great.
fun main() {
val line = readln().trim().lowercase()
val parts = line.split(" ")
val counts = mutableMapOf<String, Int>()
for (p in parts) {
if (p != "") counts[p] = (counts[p] ?: 0) + 1
}
println(counts)
}
If you enter:
Kotlin kotlin is fun
then the output will be roughly like this (the order may match insertion):
// {kotlin=2, is=1, fun=1}
Here we saw three things at the same time: string normalization (trim().lowercase()), a basic for loop, and that same counter pattern.
5. Example: “category → total” and key normalization
Now let’s carefully connect Map to our practical context: we’re gradually moving toward an app that stores records (for example, expenses) in memory. For now, without classes, we’ll represent a record as Triple(category, title, amount). Today our goal is not “perfect architecture,” but map practice: we’ll build a “by categories” report.
Let’s write a function that, given a list of records, builds a MutableMap<String, Int>, where the key is the category and the value is the total spending for that category.
fun buildTotalsByCategory(
records: List<Triple<String, String, Int>>
): Map<String, Int> {
val totals = mutableMapOf<String, Int>()
for (r in records) {
val category = r.first
val amount = r.third
totals[category] = (totals[category] ?: 0) + amount
}
return totals
}
Notice a good beginner-friendly style: inside we use MutableMap because we “build” the result, and outside we return Map because we “give it for reading.” It’s simple discipline: mutate where you create, and don’t promise mutability where it isn’t needed.
Note: there’s no conversion here. MutableMap is a subtype of Map, so we return the very same object, just under a more general type,
which only allows reading (remember: read-only is an API restriction, not immutability).
If you keep this map and continue changing it, but want to hand out an independent snapshot, return a copy: return totals.toMap().
Let’s test on a small example:
fun main() {
val records = mutableListOf<Triple<String, String, Int>>()
records.add(Triple("food", "coffee", 300))
records.add(Triple("transport", "taxi", 1200))
records.add(Triple("food", "sandwich", 250))
val totals = buildTotalsByCategory(records)
println(totals) // {food=550, transport=1200}
}
This kind of report is a core reason why Map shows up in programs more often than “pure sets” and sometimes even more often than lists: many tasks are “store an aggregated value by key.”
A nuance about keys: normalizing a string as part of the contract
Maps compare keys by exact equality. For strings, that means "Food", "food", and " food " are three different keys. And that’s not a “Kotlin problem,” it’s your future responsibility as the program author.
So if the key comes from the user (for example, they type a category), a good rule is to normalize: trim() and often lowercase(). Then your Map reflects the meaning of the data rather than random spaces and the mood of Caps Lock.
Mini example:
fun main() {
val totals = mutableMapOf<String, Int>()
val raw = " FOOD "
val category = raw.trim().lowercase()
totals[category] = (totals[category] ?: 0) + 100
println(totals) // {food=100}
}
If you don’t do this normalization, then categories like Food, FOOD, food will suddenly appear in the report — and it may feel like the program “broke,” when in fact it’s just taking the input too literally.
6. Common mistakes when working with Map/MutableMap
Mistake #1: expecting that map[key] returns V, not V?.
Beginners often write val x: Int = prices["tea"] and get surprised by a compilation error.
The compiler is your ally here: it warns that the key may be missing.
The fix is usually simple: either Elvis ?:, or a if (key in map) check, or a different function contract (for example, return Int? outward).
Mistake #2: “curing” V? with !!, because “I know the key exists.”
!! sometimes looks like a shortcut, but it’s like saying “I definitely won’t fall” before riding a scooter hands-free.
Today you’re confident, tomorrow the input data changed — and the program crashes.
It’s much calmer to either check the key, or use ?: with a clear default policy.
Mistake #3: trying to update a Map created with mapOf.
mapOf(...) returns a read-only Map. It’s for reading, not for changes.
If you need to add/remove/update, use mutableMapOf(...).
This is not pedantry: the read-only vs mutable split is an important part of Kotlin collections design.
Mistake #4: forgetting to normalize the key and getting “entity multiplication.”
When the key is a user-provided string, spaces and letter case turn into different keys.
Duplicates appear in the report “by meaning,” and you start suspecting the paranormal.
Usually it’s enough to agree on a rule: store keys as trim().lowercase(), and do “pretty display” later.
Mistake #5: storing in a Map what should conceptually be a List.
Sometimes you want to turn everything into a map because “key access is convenient there.” But if your data is naturally ordered,
if repeats or order matter, if you need positional access — those are List tasks.
Map is great when the key is truly unique and it’s logical to address it like an “address.”
Mistake #6: confusing “key” and “index” and trying to think of a map like a list.
A Map has no “zero element” and no “last index” in the sense a list does.
There are only keys. If you catch yourself wanting to “walk the map by indices,”
then you’re either solving an iteration task (we’ll cover that later), or you actually need a List.
GO TO FULL VERSION