What is the plus method of a LinkedHashMap in Kotlin?
Overview
In Kotlin, the plus method creates a new read-only Map from the current LinkedHash by adding or replacing the map entries that are passed as an argument to it.
Syntax
operator fun <K, V> Map<out K, V>.plus(
map: Map<out K, V>
): Map<K, V>
Parameters
This method takes a Map as an argument.
If the passed map contains an entry with the key already present in the LinkedHashMap, the entry’s value of the LinkedHashMap will be replaced by the value of the Map argument.
If the passed map contains an entry that is not present in the LinkedHashMap, then a new entry will be added to the LinkedHashMap.
Return value
This method returns a read-only Map by combining the current LinkedHashMap with the Map that is passed as an argument to it.
Code example
The code given below demonstrates how we can use the plus method:
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")map.put(3, "three")println("\nThe map is : $map")val argumentMap = mapOf(1 to "ONE", 4 to "FOUR")println("The argumentMap is : $argumentMap")var newMap = map.plus(argumentMap);println("\nmap.plus(argumentMap) : ${newMap}")}
Code explanation
-
Line 3: We create a new
LinkedHashMapobject withmap. We use thelinkedMapOfmethod to create an emptyLinkedHashMap. -
Lines 6–8: We add three entries to the
map{1=one,2=two,3=three}, using theputmethod. -
Line 12: We create another map with the name
argumentMap, using themapOfmethod. This map has two entries{1=ONE,4=FOUR}. -
Line 15: We use the
plusmethod withargumentMapas an argument. This method creates a newmapby combining the entries of themapwithargumentMap. In our case:- The entry
1=oneof themapwill be replaced by the entry1=ONEof theargumentMap. - A new entry
4=FOURof theargumentMapwill be added to themapobject.
- The entry
The read-only map that is returned will be {1=ONE, 2=two, 3=three, 4=FOUR}.