This article explores different ways to merge two maps in Kotlin.

1. Using + operator

A simple and fairly efficient solution to merge two maps in Kotlin is using the + operator. It can be used as follows in Kotlin:

Download Code

 
Note that for any common keys present in the maps, the latter overrides the former’s value. We can also use the plus() function to merge the contents of the specified map to the caller.

Download Code

2. Using groupBy() function

Another option is to get the sequence of all mappings contained in both maps, and then group values by the key to get a map where each group key is associated with a list of corresponding values. This is demonstrated below using the groupBy() function:

Download Code

3. Using associateWith() function

Another option is to collect all keys present in both maps and then associate each key with the set of values using the associateWith() function. Here’s complete usage of this function:

Download Code

 
The above solution results in a string of comma-separated values enclosed within []. To get a proper list of values, do like:

Download Code

4. Using apply() function

Alternatively, you can use scope functions to merge two maps. This can be implemented as follows in Kotlin using the apply() function:

Download Code

5. Using putAll() function

Finally, we can use the putAll() function to copy all entries from a map to another map. This is demonstrated below:

Download Code

 
Note that if a key exists in both maps, the value in the second map will overwrite the value in the first map:

Download Code

 
We can avoid making an extra call to the putAll() function, as follows:

That’s all about merging two maps in Kotlin.