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.
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>()
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)
size
: Returns the number of entries in the mapisEmpty()
: Checks if the map is emptycontainsKey(key)
: Checks if the map contains a specific keycontainsValue(value)
: Checks if the map contains a specific valuekeys
: Returns a set of all keys in the mapvalues
: Returns a collection of all values in the mapKotlin 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")
}
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}
mapOf()
) when the content doesn't need to changemutableMapOf()
over HashMap
for better interoperabilityTo 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.