What is the getOrPut method of LinkedHashMap in Kotlin?

Overview

The getOrPut method of LinkedHashMap will return the value associated with the key. If there is no mapping present for the key, then the default function is called. The value returned from that function is mapped to the key, and that value is returned as a return value.

Syntax

fun <K, V> MutableMap<K,V>.getOrPut(key: K, defaultValue: () -> V ): V

Parameters

This method takes two arguments:

  • key for which the value is to be retrieved.
  • defaultValue:(): This method will be invoked if no mapping is present for the key. The value returned from this function will be associated with the key.

Return value

This function returns the value associated with the key.

Code

The code below demonstrates how to use the getOrPut method in Kotlin.

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("\nThe map is : $map")
// get value for key 1
var value = map.getOrPut(1, {"Default"});
println("getOrPut(1, {'Default'}) : $value")
value = map.getOrPut(5, {"Default"});
println("getOrPut(5, {'Default'}) : $value")
println("\nThe map is : $map")
}

Explanation

  • Line 3: We created a new LinkedHashMap object with map. We use the linkedMapOf method to create an empty LinkedHashMap.

  • Lines 6–7: We add two new entries, {1=one, 2=two}, to the map using the put() method.

  • Line 11: We use the getOrPut method the key 1 and the default value function returning the string Default. In our case, there is a mapping for the key 1, so the mapped value "one" is returned.

  • Line 14: We use the getOrPut method with the key 5 and the default value function returning the string Default. In our case, there is no mapping for the key 5, so the default value function will be invoked, and the value returned from that function will be mapped to the key 5. The value Default will be mapped to the key 5, returning the value.

Free Resources