This article explores different ways to put all entries of a Map to another Map in Kotlin.

1. Using putIfAbsent() function

The putIfAbsent() function is used to associate the specified key with a value if the key is not present in the map. The idea is to iterate over each entry of the second map and invoke the putIfAbsent() function on the first map for each mapping of the second map.

Download Code

Output:

{1=A, 2=B, 3=C, 4=D}

 
This effectively copies all mappings of the second map to the first map and does not replace the existing mappings in the first map. For instance,

Download Code

Output:

{1=A, 2=B, 3=D}

2. Using merge() function

A better alternative is to use the merge() function to associate the existing key with the old value or the new value. It takes the remapping function to recompute the value if already present.

The following code demonstrates its usage with a remapping function, where the new value takes precedence over the old value if the key is already present:

Download Code

Output:

{1=A, 2=C, 3=D}

 
We can shorten the code using forEach() to iterate over each mapping in the map.

Download Code

Output:

{1=A, 2=C, 3=D}

3. Using containsKey() function

We can also iterate over each entry in the second map and add the mapping if and only if the key is not already present in the first map.

Download Code

Output:

{1=A, 2=B, 3=D}

4. Using + operator

To create a new map that is the combination of both maps, we can use the + operator or the plus() function. It replaces the existing mappings in the first map from the mappings of the second map. For instance,

Download Code

Output:

{1=A, 2=C, 3=D}

5. Using groupBy() function

The idea is to create a sequence of both maps entries and group them by key using the groupBy() function. Finally, map their values to comma-separated strings, resulting in a multimap-like structure.

Download Code

Output:

{1=[A], 2=[B, C], 3=[D]}

 
Alternatively, we can use the associateWith() function as follows:

Download Code

Output:

{1=[A], 2=[B, C], 3=[D]}

That’s all about putting all Map’s entries to another Map in Kotlin.