Kotlin Map getOrDefault()
Syntax & Examples


Syntax of Map.getOrDefault()

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.



✐ Examples

1 Get value for an existing key in the map

In this example,

  • We create a map named map with integer keys and character values.
  • We use the getOrDefault() function to retrieve the value for key 2. Since key 2 exists in the map, its corresponding value 'b' is returned.
  • The result, which is 'b', is printed to standard output.

Kotlin Program

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)
}

Output

b

2 Get value for an existing key in the map with a default value

In this example,

  • We create a map named map with string keys and integer values.
  • We use the getOrDefault() function to retrieve the value for key 'banana'. Since key 'banana' exists in the map, its corresponding value 2 is returned.
  • The result, which is 2, is printed to standard output.

Kotlin Program

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)
}

Output

2

3 Get default value for a non-existing key in the map

In this example,

  • We create a map named map with integer keys and character values.
  • We use the getOrDefault() function to retrieve the value for key 4. Since key 4 does not exist in the map, the default value 'z' is returned.
  • The result, which is 'z', is printed to standard output.

Kotlin Program

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)
}

Output

z

Summary

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.