Maps
A Map is a collection of key-value pairs where each key is unique. Maps are highly optimized for fast data retrieval by key.
Creating Maps
Initialize a Map using the explicit constructor or via the syntactic sugar with curly braces. You must specify both the Key type and the Value type.
// 1. Explicit Constructor
val explicitMap = Map<String, Int>()
println("Is empty? ${if (explicitMap.isEmpty()) "Yes" else "No"}")
// 2. Sugar Syntax
val inventory = <String, Int>{"Apple": 10, "Banana": 20, "Cherry": 30}
println("Size is: ${inventory.size()}") // 3Accessing & Modifying
Use set() to add or update pairs. Use get() to retrieve values — it returns an optional type (V?) that is null when the key doesn't exist.
val m = <String, Int>{"Apple": 10}
// Retrieve a value (m["Apple"] == m.get("Apple"))
println(m["Apple"]) // 10
println(m["Durian"]) // null
// Update an existing key (m["Apple"] = 15 == m.set("Apple", 15))
m["Apple"] = 15
// Check if a key exists
val hasCherry = m.containsKey("Cherry") // false
// Remove a key-value pair
m.remove("Apple")
m.clear() // Empties the entire mapIteration & Views
Iterate over the Map using forEach() with a closure. Extract all keys or all values into separate Arrays using keys() and values().
val numMap = <Int, Int>{1: 100, 2: 200, 3: 300}
// Iterate using a single-expression closure
numMap.forEach {|key, value| println("Key: ${key}, Value: ${value}") }
// Iterate using a block-body closure
var total = 0
numMap.forEach {|key, value| -> {
total = total + value
}}
println("Sum of all values: ${total}")
// Extract Keys and Values into Arrays
val keysArr = numMap.keys() // [1, 2, 3]
val valuesArr = numMap.values() // [100, 200, 300]Methods Reference
Modification
set(key: K, value: V)— Inserts a new pair or updates the value if the key already exists.remove(key: K)— Removes the key and its corresponding value.clear()— Removes all key-value pairs.
Querying
get(key: K): V?— Returns the value ornullif the key does not exist.getOrDefault(key: K, defaultValue: V): V— Returns the value or a fallback default.containsKey(key: K): Bool— Returns true if the Map contains the specified key.size(): Int— Returns the total number of key-value pairs.isEmpty(): Bool— Returns true if the Map contains 0 items.
Iteration & Utility
forEach(fn: (K, V) -> Void)— Executes a closure once for each key-value pair.keys(): Array<K>— Returns a new Array containing all keys.values(): Array<V>— Returns a new Array containing all values.toString(): String— Returns a string representation of the Map.
