This article explores different ways to merge values in a map in Kotlin.

1. Using groupBy() function

The idea is to get a distinct list of all mappings and group values by the key such that we get a map where each group key is associated with a list of corresponding values. This would translate to a simple code below using the groupBy() function:

Download Code

2. Using associateWith() function

Another good approach is to collect all keys present in the Map and then associate each key with the set of values using the associateWith() function. Here’s an example of its usage:

Download Code

That’s all about merging two maps in Kotlin.