Map<K, V>
8 methodsA collection that holds pairs of keys and values. Map is read-only; MutableMap supports modification.
Map.size: IntReturns the number of key-value pairs in this map.
Returns
Int
Example
val m = mapOf("a" to 1, "b" to 2)
println(m.size) // 2Map.containsKey(key: K): BooleanReturns true if the map contains the specified key.
Parameters
| Name | Type | Description |
|---|---|---|
| key | K | Key to check. |
Returns
Boolean
Example
val m = mapOf("a" to 1, "b" to 2)
println(m.containsKey("a")) // true
println(m.containsKey("c")) // falseMap.containsValue(value: V): BooleanReturns true if the map maps one or more keys to the specified value.
Parameters
| Name | Type | Description |
|---|---|---|
| value | V | Value to check. |
Returns
Boolean
Example
val m = mapOf("a" to 1, "b" to 2)
println(m.containsValue(2)) // true
println(m.containsValue(9)) // falseMap.get(key: K): V?Returns the value corresponding to the given key, or null if not present.
Parameters
| Name | Type | Description |
|---|---|---|
| key | K | Key to look up. |
Returns
V?
Example
val m = mapOf("a" to 1, "b" to 2)
println(m.get("a")) // 1
println(m["c"]) // nullMutableMap.put(key: K, value: V): V?Associates the specified value with the specified key. Returns the previous value (or null).
Parameters
| Name | Type | Description |
|---|---|---|
| key | K | Key to set. |
| value | V | Value to associate. |
Returns
V?
Example
val m = mutableMapOf("a" to 1)
val old = m.put("a", 10)
// old == 1, m["a"] == 10
m["b"] = 2 // shorthand
// m == {a=10, b=2}MutableMap.remove(key: K): V?Removes the specified key and its corresponding value. Returns the removed value (or null).
Parameters
| Name | Type | Description |
|---|---|---|
| key | K | Key to remove. |
Returns
V?
Example
val m = mutableMapOf("a" to 1, "b" to 2)
val removed = m.remove("a")
// removed == 1, m == {b=2}Map.forEach { (key, value) -> Unit }Performs the given action on each entry in the map.
Parameters
| Name | Type | Description |
|---|---|---|
| action | (Entry<K, V>) -> Unit | Action lambda. |
Returns
Unit
Example
val m = mapOf("a" to 1, "b" to 2)
m.forEach { (k, v) -> println("$k=$v") }
// prints:
// a=1
// b=2Map.keys: Set<K>Returns a read-only Set of all keys in this map.
Returns
Set<K>
Example
val m = mapOf("a" to 1, "b" to 2)
println(m.keys) // [a, b]