keys and values are both user-defined maps. so for retrieving a value, key should be provided as an argument of the get() function. The shorthand [key] syntax is also supported. If key is not found, null is returned. There is one more different function getValue() : it throws an exception if the key is not found in the map.
Also there are two more options to handle the key absence:
getOrElse() is same as for lists: the values for non-existent keys are returned from the given lambda function.
getOrDefault() returns the specified default value if the key is not found.
fun main() {
val numbersMap = mapOf("elevan" to 11, "twelve" to 12, "thirteen" to 13)
println(numbersMap.get("elevan"))
println(numbersMap\["elevan"\])
println(numbersMap.getOrDefault("fourteen", 10))
println(numbersMap\["fifteen"\]) // null
}
11
11
10
null
Filter
filter operation can be done on maps with the filter() function . When calling filter() on a map, pass to it a predicate with a Pair as an argument. This enables to use of both the key and the value in the filtering predicate.
val numbersMap = mapOf("key11" to 11, "key22" to 22, "key33" to 33, "key11" to 11)
val filteredMap = numbersMap.filter { (key, value) -> key.endsWith("1") && value > 10}
println(filteredMap)
{key11=11}
Map write operations
Mutable maps offer map-specific write operations. map content can be changed using the key-based access to the values.
There are certain rules that define write operations on maps:
Values can be updated. In turn, keys are final : once you add an entry, its key is constant.
For each key, there is always a single value associated with it. You can add and remove whole entries.
Below are descriptions of the standard library functions for write operations
Add and update entries
put() is used to add a new key-value pair to a mutable map. When a new entry is put into a LinkedHashMap (the default map implementation), it is added so that it comes last while iterating the map. However n sorted maps, the positions of new elements are defined by the order of their keys.
val numbersMap = mutableMapOf("elevan" to 11, "twelve" to 22)
numbersMap.put("thirteen", 33)
println(numbersMap)
{elevan=11, twelve=22, thirteen=33}
Remove entries
To remove an entry from a mutable map, remove() function is used. When calling remove(), either a key or a whole key-value-pair can be pass. For specified key and value, the element with this key will be removed only if its value matches the second argument.
val numbersMap = mutableMapOf("elevan" to 11, "twelve" to 12, "thirteen" to 13)
numbersMap.remove("elevan")
println(numbersMap)
numbersMap.remove("thirteen", 4) //doesn't remove anything
println(numbersMap)
{twelve=12, thirteen=13}
{twelve=12, thirteen=13}