🗺️ Kotlin – Maps (Key-Value Pairs): Organize Data with Keys
🧲 Introduction – Why Learn Kotlin Maps?
Maps are one of the most essential collection types in Kotlin, allowing you to store key-value pairs efficiently. They’re perfect for scenarios like lookup tables, configuration settings, or JSON-like structures. Kotlin provides immutable and mutable Maps with powerful utilities and clean syntax.
🎯 In this guide, you’ll learn:
- How to declare and use Kotlin Maps
- The difference between immutable (
mapOf
) and mutable (mutableMapOf
) maps - Access, update, and iterate over key-value data
- Best practices for map operations in real apps
🧾 What Is a Map in Kotlin?
A Map is a collection of key-value pairs. Each key is unique and maps to a value.
- Keys → Unique
- Values → Can be duplicated
- Keys are used to retrieve or update values
🛡️ Immutable Maps – mapOf()
val countries = mapOf("IN" to "India", "US" to "United States")
println(countries["IN"]) // India
println(countries["FR"]) // null (not found)
- Cannot be modified after creation
- Great for constants and static data
🛠️ Mutable Maps – mutableMapOf()
val codes = mutableMapOf("A" to 1, "B" to 2)
codes["C"] = 3
codes.remove("A")
println(codes) // {B=2, C=3}
- You can add, remove, or update entries freely
🔁 Iterating Over a Map
🔹 Loop with entries
:
for ((key, value) in countries) {
println("$key => $value")
}
🔹 Loop over keys or values only:
for (key in countries.keys) {
println("Code: $key")
}
for (value in countries.values) {
println("Country: $value")
}
🧪 Common Map Functions
Function | Description |
---|---|
get(key) | Returns value for the given key |
getOrDefault(key, v) | Returns value or default if key not found |
containsKey(key) | Checks if a key exists in the map |
containsValue(value) | Checks if a value exists |
put(key, value) | Adds or updates entry (mutable only) |
remove(key) | Removes entry by key (mutable only) |
isEmpty() | Checks if the map has no entries |
🧬 Map Type Variants
Type | Description |
---|---|
HashMap | Unordered, fast lookup |
LinkedHashMap | Maintains insertion order |
TreeMap (Java) | Sorted by key (requires Java interop) |
val orderedMap = linkedMapOf("one" to 1, "two" to 2)
println(orderedMap) // {one=1, two=2}
🔄 Convert Lists to Maps
val users = listOf("Alice", "Bob")
val userMap = users.associateWith { it.length }
println(userMap) // {Alice=5, Bob=3}
✔️ Turns a list into a map based on a transformation.
🚫 Common Mistakes
❌ Mistake | ✅ Fix |
---|---|
Trying to modify mapOf() | Use mutableMapOf() or convert using .toMutableMap() |
Using missing keys without null check | Use getOrDefault() or getOrElse() for safety |
Confusing map with set/list | Map uses keys and values; not just values |
Assuming key order in mapOf() | Use linkedMapOf() to maintain order |
✅ Best Practices for Kotlin Maps
Tip | Why It Helps |
---|---|
Use mapOf() for static configurations | Prevents accidental mutations |
Use getOrDefault() for safe access | Avoids null crashes |
Use entries , keys , values for iteration | Enhances readability |
Choose correct map type (LinkedHashMap , HashMap ) | Based on ordering needs |
📌 Summary – Recap & Next Steps
Kotlin Maps are ideal for keyed data access, such as ID-to-name lookups, field-value mappings, or configuration tables. With both immutable and mutable forms, plus built-in functions, Maps offer a clean and safe way to organize and access data.
🔍 Key Takeaways:
- Use
mapOf()
for immutable maps,mutableMapOf()
for editable ones - Each key is unique; values can repeat
- Retrieve data using keys, safely handle missing entries
- Use map functions to filter, transform, and combine data
⚙️ Practical Use:
Maps are essential for user ID-to-data maps, API headers, language/localization dictionaries, and dynamic form field storage in Android and backend Kotlin applications.
❓ FAQs – Kotlin Maps
❓ What is a Kotlin Map used for?
✅ A Map stores key-value pairs for fast lookup, transformation, or matching logic.
❓ How do I create a mutable Map in Kotlin?
✅ Use mutableMapOf()
:
val m = mutableMapOf("A" to 1)
m["B"] = 2
❓ Can I access a key that doesn’t exist in a map?
✅ Yes, but it returns null
or use getOrDefault()
:
map.getOrDefault("X", "Unknown")
❓ Are Maps ordered in Kotlin?
✅ By default, no. Use linkedMapOf()
or LinkedHashMap
for insertion order.
❓ Can I filter a map by values or keys?
✅ Yes:
val filtered = map.filter { it.value > 10 }
Share Now :