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.
fun <K, V> MutableMap<K,V>.getOrPut(key: K, defaultValue: () -> V ): V
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.This function returns the value associated with the key.
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 valueval map: LinkedHashMap<Int, String> = linkedMapOf()// add two entriesmap.put(1, "one")map.put(2, "two")println("\nThe map is : $map")// get value for key 1var 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")}
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.