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.
fun <K, V> Map<K, V>.getOrElse(key: K,defaultValue: () -> V): V
This method takes two arguments:
key for which a value to be returned is passed as an argument.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.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 valueval map: LinkedHashMap<Int, String> = linkedMapOf()// add two entriesmap.put(1, "one")map.put(2, "two")println("The map is : $map")// get value for key 1var value = map.getOrElse(1, {"Default"});println("getOrElse(1, {'Default'}) : $value")value = map.getOrElse(5, {"Default"});println("getOrElse(5, {'Default'}) : $value")}
LinkedHashMap object named map. We use the linkedMapOf method to create an empty LinkedHashMap.map using the put() method.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.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.