
Maps in Kotlin
📌 Maps in Kotlin
In Kotlin, a Map is a collection of key-value pairs where keys are unique, and each key is associated with exactly one value. Maps are useful when you want to store data in a key-value format, like a dictionary.
Kotlin provides two types of Maps:
Immutable Map (
Map
) → Read-only (Cannot be modified).Mutable Map (
MutableMap
) → Can be modified (Add, Remove, or Update key-value pairs).
✅ 1. Creating Maps in Kotlin
📌 Immutable Map
Use
mapOf()
to create a read-only map.
fun () { val fruits = mutableMapOf("Apple" to 5, "Banana" to 10, "Orange" to 7) println(fruits) // Adding a new key-value pair fruits["Mango"] = 12 // Removing a key fruits.remove("Banana") // Updating a value fruits["Apple"] = 8 println(fruits)}
Output:
{Apple=5, Banana=10, Orange=7}{Apple=8, Orange=7, Mango=12}
fruits["key"] = value
→ Add or Update.remove()
→ Remove a key-value pair.
✅ 2. Accessing Map Elements
You can access map elements using the key:
📌 Example:
val capitals = mapOf("France" to "Paris", "Italy" to "Rome", "Germany" to "Berlin")println("Capital of France: ${capitals["France"]}") println(Capital of France: ParisCapital of Spain: Not Found
map[key]
→ Returns value ornull
if the key doesn't exist.?:
→ Provides a default value using the Elvis operator.
✅ 3. Map Functions in Kotlin
Function | Description | Example |
---|---|---|
keys | Returns all keys | map.keys |
values | Returns all values | map.values |
entries | Returns key-value pairs | map.entries |
get() | Returns the value for a key | map.get("key") |
containsKey() | Checks if a key exists | map.containsKey("key") |
containsValue() | Checks if a value exists | map.containsValue("value") |
isEmpty() | Checks if the map is empty | map.isEmpty() |
size | Returns the number of key-value pairs | map.size |
✅ 4. Iterating Through a Map
📌 Using For Loop:
val students = mapOf(101 to "John", 102 to "Emma", 103 to "Liam")for ((id, name) in students) { println("Student ID: $id, Name: Student ID: 101, Name: JohnStudent ID: 102, Name: EmmaStudent ID: 103, Name: Liam
Destructure using
(key, value)
inside the loop.
📌 Using forEach:
students.forEach { (key, value) -> println("$key -> 101 -> John102 -> Emma103 -> Liam
✅ 5. Filtering Maps
You can filter key-value pairs using filter
or filterKeys
.
📌 Filter by Values:
val products = mapOf("Laptop" to 50000, "Phone" to 30000, "Tablet" to 20000)val expensiveProducts = products.filter { it.value > 30000 }println(expensiveProducts)
Output:
{Laptop=50000}
📌 Filter by Keys:
val filteredKeys = products.filterKeys { it.startsWith("P") }println(filteredKeys)
Output:
{Phone=30000}
✅ 6. Map Transformations
You can transform maps using mapValues()
or mapKeys()
.
📌 Example:
val numbers = mapOf(1 to 10, 2 to 20, 3 to 30)// Double the valuesval doubledValues = numbers.mapValues { it.value * 2 }println(doubledValues)// Prefix keysval prefixedKeys = numbers.mapKeys { "Key${it.key}" }println(prefixedKeys)
Output:
{1=20, 2=40, 3=60}{Key1=10, Key2=20, Key3=30}
✅ 7. Conclusion
Use
mapOf()
for immutable maps andmutableMapOf()
for mutable ones.Access elements using
map[key]
orget()
.Use
filter
,mapValues
, ormapKeys
for transformations.Iterate using
for
loops orforEach
.Efficient for representing key-value data like dictionaries, configurations, and mappings.