Add key-value pairs to a map in Kotlin
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.
|
1 2 3 4 5 6 7 8 9 |
fun main() { val map: MutableMap<Char, Int> = mutableMapOf(Pair('A', 1), Pair('B', 2), Pair('C', 3)) map['D'] = 4 map.set('E', 5) map.set('F', 6) println(map) } |
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.
|
1 2 3 4 5 6 7 8 |
fun main() { val map: MutableMap<Char, Int> = mutableMapOf(Pair('A', 1), Pair('B', 2), Pair('C', 3)) map.putIfAbsent('A', 0) map.putIfAbsent('D', 4) println(map) } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
fun insertToMultiMap(map: MutableMap<String, MutableList<String>>, key: String, value: MutableList<String>) { if (map.containsKey(key)) { map[key]!!.addAll(value) } else { map[key] = value } } fun main() { val map: MutableMap<String, MutableList<String>> = mutableMapOf( Pair("White", mutableListOf("#FFFFFF", "#ffffff")), Pair("Black", mutableListOf("#000000")) ) insertToMultiMap(map, "White", mutableListOf("#FFF", "#fff")) insertToMultiMap(map, "Black", mutableListOf("#000")) insertToMultiMap(map, "Blue", mutableListOf("#0000FF", "#0000ff")) println(map) } |
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.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)