Kotlin Map get()
Syntax & Examples
Syntax of Map.get()
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.
✐ Examples
1 Get value corresponding to specified key (present)
In this example,
- We create a map named
map1
containing pairs of numbers and characters. - We then retrieve the value corresponding to the key
2
using theget()
function. - As
2
is present in the keys ofmap1
, the corresponding value'b'
is returned. - We print the result to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map1 = mapOf(1 to 'a', 2 to 'b', 3 to 'c')
val value1 = map1.get(2)
println(value1)
}
Output
b
2 Get value corresponding to specified key (not present)
In this example,
- We create a map named
map2
containing pairs of characters and numbers. - We then attempt to retrieve the value corresponding to the key
'd'
using theget()
function. - As
'd'
is not present in the keys ofmap2
,null
is returned. - We print the result to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map2 = mapOf('a' to 1, 'b' to 2, 'c' to 3)
val value2 = map2.get('d')
println(value2)
}
Output
null
3 Get value corresponding to specified key (present)
In this example,
- We create a map named
map3
containing pairs of strings and numbers. - We then retrieve the value corresponding to the key
'banana'
using theget()
function. - As
'banana'
is present in the keys ofmap3
, the corresponding value2
is returned. - We print the result to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map3 = mapOf("apple" to 1, "banana" to 2, "cherry" to 3)
val value3 = map3.get("banana")
println(value3)
}
Output
2
Summary
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.