What is the getOrElse method of LinkedHashMap in Kotlin?

The getOrElse method can safely get the value of the key. The method provides a default value for the key when there is no mapping for a specific key present in the LinkedHashMap.

Syntax

fun <K, V> Map<K, V>.getOrElse(
key: K,
defaultValue: () -> V
): V
Syntax of getOrElse method

Parameters

This method takes two arguments:

  • The key for which a value to be returned is passed as an argument.
  • The default value function. The value returned from that function will be returned as a result of the mapping if the passed key is not present.

Return value

This method returns the value associated with the key. If the mapping for the key is not present, the default value is returned.

fun main() {
//create a new LinkedHashMap which can have integer type as key, and string type as value
val map: LinkedHashMap<Int, String> = linkedMapOf()
// add two entries
map.put(1, "one")
map.put(2, "two")
println("The map is : $map")
// get value for key 1
var value = map.getOrElse(1, {"Default"});
println("getOrElse(1, {'Default'}) : $value")
value = map.getOrElse(5, {"Default"});
println("getOrElse(5, {'Default'}) : $value")
}

Explanation

  • Line 3: We create a new LinkedHashMap object named map. We use the linkedMapOf method to create an empty LinkedHashMap.
  • Lines 5 - 6: We add two new entries {1=one, 2=two} to the map using the put() method.
  • Line 9: We use the getOrElse method with the key 1 and the default value 'Default'. In our case, there is a mapping for the key 1, so the mapped value One is returned.
  • Line 11: We use the getOrElse method with the key 5 and the default value 'Default'. In our case, there is no mapping for the key 5, so the default value Default is returned.