Start Coding

Topics

Kotlin Maps

Maps in Kotlin are powerful collection types that store key-value pairs. They provide an efficient way to organize and retrieve data based on unique keys.

Creating Maps

Kotlin offers several ways to create maps:


// Using mapOf() function
val readOnlyMap = mapOf("key1" to "value1", "key2" to "value2")

// Using mutableMapOf() for mutable maps
val mutableMap = mutableMapOf<String, Int>()

// Using HashMap
val hashMap = HashMap<String, Double>()
    

Accessing and Modifying Map Elements

You can access map elements using square bracket notation or the get() function:


val map = mapOf("name" to "John", "age" to 30)

println(map["name"]) // Output: John
println(map.get("age")) // Output: 30

// For mutable maps, you can modify values
val mutableMap = mutableMapOf("x" to 1, "y" to 2)
mutableMap["x"] = 10
mutableMap.put("z", 3)
    

Useful Map Operations

  • size: Returns the number of entries in the map
  • isEmpty(): Checks if the map is empty
  • containsKey(key): Checks if the map contains a specific key
  • containsValue(value): Checks if the map contains a specific value
  • keys: Returns a set of all keys in the map
  • values: Returns a collection of all values in the map

Iterating Over Maps

Kotlin provides convenient ways to iterate over maps:


val fruitInventory = mapOf("apples" to 5, "bananas" to 8, "oranges" to 3)

// Iterate over entries
for ((fruit, quantity) in fruitInventory) {
    println("We have $quantity $fruit")
}

// Iterate over keys
for (fruit in fruitInventory.keys) {
    println("Fruit: $fruit")
}

// Iterate over values
for (quantity in fruitInventory.values) {
    println("Quantity: $quantity")
}
    

Map Transformations

Kotlin's standard library offers various functions for map transformations:


val numbers = mapOf("one" to 1, "two" to 2, "three" to 3)

// Filter
val evenNumbers = numbers.filter { (_, value) -> value % 2 == 0 }

// Map transformation
val doubled = numbers.mapValues { (_, value) -> value * 2 }

// Merge two maps
val map1 = mapOf("a" to 1, "b" to 2)
val map2 = mapOf("b" to 3, "c" to 4)
val merged = map1 + map2 // Result: {"a" to 1, "b" to 3, "c" to 4}
    

Best Practices

  • Use immutable maps (mapOf()) when the content doesn't need to change
  • Prefer mutableMapOf() over HashMap for better interoperability
  • Use Kotlin Nullable Types for keys or values that might be null
  • Consider using Kotlin Data Classes as map keys for complex objects

Related Concepts

To further enhance your understanding of Kotlin collections, explore these related topics:

Maps are essential data structures in Kotlin programming. They offer efficient key-value storage and retrieval, making them ideal for various applications such as caching, data organization, and complex data relationships.