The syntax of Map.getOrDefault() function is:
open fun getOrDefault(key: K, defaultValue: V): V
This getOrDefault() function of Map returns the value corresponding to the given key, or defaultValue if such a key is not present in the map.
In this example,
map
with integer keys and character values.getOrDefault()
function to retrieve the value for key 2
. Since key 2
exists in the map, its corresponding value 'b'
is returned.'b'
, is printed to standard output.fun main(args: Array<String>) {
val map = mapOf(1 to 'a', 2 to 'b', 3 to 'c')
val result = map.getOrDefault(2, 'z')
println(result)
}
b
In this example,
map
with string keys and integer values.getOrDefault()
function to retrieve the value for key 'banana'
. Since key 'banana'
exists in the map, its corresponding value 2
is returned.2
, is printed to standard output.fun main(args: Array<String>) {
val map = mapOf("apple" to 1, "banana" to 2, "cherry" to 3)
val result = map.getOrDefault("banana", -1)
println(result)
}
2
In this example,
map
with integer keys and character values.getOrDefault()
function to retrieve the value for key 4
. Since key 4
does not exist in the map, the default value 'z'
is returned.'z'
, is printed to standard output.fun main(args: Array<String>) {
val map = mapOf(1 to 'a', 2 to 'b', 3 to 'c')
val result = map.getOrDefault(4, 'z')
println(result)
}
z
In this Kotlin tutorial, we learned about getOrDefault() function of Map: the syntax and few working examples with output and detailed explanation for each example.