Maps

A map is collection of key-value pairs.

Map interface represents immutable map. You can create instance from any Java map class or from factory function mapOf(). Default implementation is LinkedHashMap class.

MutableMap interface represents mutable map. You can create instance from any Java map class or from factory function mutableMapOf().

Entry interface represents a key-value pair for maps.

val numbersMap1 = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key4" to 1)
val numbersMap2 = mutableMapOf("one" to 1, "two" to 2)

println("All keys: ${numbersMap1.keys}")
println("All values: ${numbersMap1.values}")

numbersMap2.put("three", 3)
numbersMap2["one"] = 11
numbersMap.remove("one")

You can iterate over map using for-in loop or forEach() method.

for ((k, v) in items) {
    println("$k : $v")
}

items.forEach { k, v ->       
    println("$k = $v")
}

You can filter maps with the filter() function as well as other collections. There are also two specific ways for filtering maps: by keys and by values via filterKeys() and filterValues() functions. Both return a new map of entries which match the given predicate.

val filteredMap = numbersMap.filter { (key, value) -> key.endsWith("1") && value > 10}
val filteredKeysMap = numbersMap.filterKeys { it.endsWith("1") }
val filteredValuesMap = numbersMap.filterValues { it < 10 }

There are map specific operators:

  • [] - put()/get() methods
  • in - contains()
  • + - union map with other map or Pair. Entries from left operand will be replaced by enties from right operand if necessary.
  • - - removes from left operand entries with keys specified in right operand. The right operand can be either a single key or a collection of keys: list, set, and so on.
val numbersMap = mapOf("one" to 1, "two" to 2, "three" to 3)
if ("key2" in numbersMap) println("Value by key \"key2\": ${numbersMap["key2"]}")    

if (1 in numbersMap.values) println("The value 1 is in the map")

if (numbersMap.containsValue(1)) 
    println("The value 1 is in the map") // same as previous

println(numbersMap.get("one"))
println(numbersMap["one"])
numbersMap["one"] = 111 // now "one" map to the 111

println(numbersMap + Pair("one", 10))
println(numbersMap + mapOf("five" to 5, "one" to 11))

println(numbersMap - "one")
println(numbersMap - listOf("two", "four"))