To add a key-value pair to a map in Kotlin, you can use the plus operator or the put method.
We can add a key-value pair to an immutable map in Kotlin using the plus operator, which returns a new map with the specified key and value added.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.println
.fun main() {
// Declare and initialize an immutable map
val myMap = mapOf(
"one" to 1,
"two" to 2,
"three" to 3
)
// Add a key-value pair using plus operator
val updatedMap = myMap + ("four" to 4)
// Print the updated map
for ((key, value) in updatedMap) {
println("$key: $value")
}
}
one: 1 two: 2 three: 3 four: 4
We can add a key-value pair to a mutable map in Kotlin using the put method, which associates the specified value with the specified key in the map.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.put
method to add a new key-value pair to the map. The put
method takes two arguments: the key and the value to be added.println
.fun main() {
// Declare and initialize a mutable map
val myMap = mutableMapOf(
"one" to 1,
"two" to 2,
"three" to 3
)
// Add a key-value pair using put method
myMap.put("four", 4)
// Print the updated map
for ((key, value) in myMap) {
println("$key: $value")
}
}
one: 1 two: 2 three: 3 four: 4
We can add multiple key-value pairs to a mutable map in Kotlin using the putAll method, which adds all key-value pairs from another map.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.putAll
method to add multiple new key-value pairs to the map. The putAll
method takes another map containing the key-value pairs to be added.println
.fun main() {
// Declare and initialize a mutable map
val myMap = mutableMapOf(
"one" to 1,
"two" to 2,
"three" to 3
)
// Add multiple key-value pairs using putAll method
myMap.putAll(mapOf("four" to 4, "five" to 5))
// Print the updated map
for ((key, value) in myMap) {
println("$key: $value")
}
}
one: 1 two: 2 three: 3 four: 4 five: 5
In this tutorial, we learned How to Add a Key-Value Pair to a Map in Kotlin language with well detailed examples.