The syntax of Map.get() function is:
abstract operator fun get(key: K): V?
This get() function of Map returns the value corresponding to the given key, or null if such a key is not present in the map.
In this example,
map1
containing pairs of numbers and characters.2
using the get()
function.2
is present in the keys of map1
, the corresponding value 'b'
is returned.fun main(args: Array<String>) {
val map1 = mapOf(1 to 'a', 2 to 'b', 3 to 'c')
val value1 = map1.get(2)
println(value1)
}
b
In this example,
map2
containing pairs of characters and numbers.'d'
using the get()
function.'d'
is not present in the keys of map2
, null
is returned.fun main(args: Array<String>) {
val map2 = mapOf('a' to 1, 'b' to 2, 'c' to 3)
val value2 = map2.get('d')
println(value2)
}
null
In this example,
map3
containing pairs of strings and numbers.'banana'
using the get()
function.'banana'
is present in the keys of map3
, the corresponding value 2
is returned.fun main(args: Array<String>) {
val map3 = mapOf("apple" to 1, "banana" to 2, "cherry" to 3)
val value3 = map3.get("banana")
println(value3)
}
2
In this Kotlin tutorial, we learned about get() function of Map: the syntax and few working examples with output and detailed explanation for each example.