Skip to content

Kotlin kotlin.collections.Map API

Kotlin's Map<K, V> — an immutable key-value collection; MutableMap<K, V> adds mutation.

1 class · 8 methods

Map<K, V>

8 methods

A collection that holds pairs of keys and values. Map is read-only; MutableMap supports modification.

Map.size: Int

Returns the number of key-value pairs in this map.

Returns

Int

Example

kotlin
val m = mapOf("a" to 1, "b" to 2)
println(m.size)  // 2
Map.containsKey(key: K): Boolean

Returns true if the map contains the specified key.

Parameters

NameTypeDescription
keyKKey to check.

Returns

Boolean

Example

kotlin
val m = mapOf("a" to 1, "b" to 2)
println(m.containsKey("a"))  // true
println(m.containsKey("c"))  // false
Map.containsValue(value: V): Boolean

Returns true if the map maps one or more keys to the specified value.

Parameters

NameTypeDescription
valueVValue to check.

Returns

Boolean

Example

kotlin
val m = mapOf("a" to 1, "b" to 2)
println(m.containsValue(2))  // true
println(m.containsValue(9))  // false
Map.get(key: K): V?

Returns the value corresponding to the given key, or null if not present.

Parameters

NameTypeDescription
keyKKey to look up.

Returns

V?

Example

kotlin
val m = mapOf("a" to 1, "b" to 2)
println(m.get("a"))  // 1
println(m["c"])      // null
MutableMap.put(key: K, value: V): V?

Associates the specified value with the specified key. Returns the previous value (or null).

Parameters

NameTypeDescription
keyKKey to set.
valueVValue to associate.

Returns

V?

Example

kotlin
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

NameTypeDescription
keyKKey to remove.

Returns

V?

Example

kotlin
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

NameTypeDescription
action(Entry<K, V>) -> UnitAction lambda.

Returns

Unit

Example

kotlin
val m = mapOf("a" to 1, "b" to 2)
m.forEach { (k, v) -> println("$k=$v") }
// prints:
// a=1
// b=2
Map.keys: Set<K>

Returns a read-only Set of all keys in this map.

Returns

Set<K>

Example

kotlin
val m = mapOf("a" to 1, "b" to 2)
println(m.keys)  // [a, b]