This article explores different ways to add key-value pairs to a map in Kotlin.

1. Insert entries to a Map

The standard solution to add key-value pairs to a mutable map is using the indexing operator, which associates the specified value with the specified key in the map. This is equivalent to using the set() or the put() function.

Download Code

Output:

{A=1, B=2, C=3, D=4, E=5, F=6}

 
If the map already contains the specified key, the old value will be replaced by the new value. You can avoid that by using the putIfAbsent() function. It associates the specified key with the specified value if and only the key is not present in the map.

Download Code

Output:

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

2. Add entries to a MultiMap

The default behavior of map enforces each key to be associated with only a single value. You can use a MultiMap that allows the mapping of a key with multiple values. Since there is no direct implementation of the MultiMap, you can mimic its behavior by maintaining a collection of values for the same key. This can be implemented as follows in Kotlin.

Download Code

Output:

{White=[#FFFFFF, #ffffff, #FFF, #fff], Black=[#000000, #000], Blue=[#0000FF, #0000ff]}

That’s all about adding key-value pairs to a map in Kotlin.