To update the value for a key in a map in Kotlin, you can use the subscript operator or the put method. These methods allow you to modify the value associated with a specific key directly.
We can update the value for a key in a map in Kotlin using the subscript operator, which allows us to modify the value associated with a specific key directly.
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 a mutable map
val myMap = mutableMapOf(
"one" to 1,
"two" to 2,
"three" to 3
)
// Update the value using subscript operator
myMap["two"] = 22
// Print the updated map
for ((key, value) in myMap) {
println("$key: $value")
}
}
one: 1 two: 22 three: 3
We can update the value for a key in a map in Kotlin using the put method, which allows us to modify the value associated with a specific key directly.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.put
method to update the value for a specific key in the map. The put
method takes the key and the new value to be assigned.println
.fun main() {
// Declare and initialize a mutable map
val myMap = mutableMapOf(
"one" to 1,
"two" to 2,
"three" to 3
)
// Update the value using put method
myMap.put("two", 22)
// Print the updated map
for ((key, value) in myMap) {
println("$key: $value")
}
}
one: 1 two: 22 three: 3
We can update the value for a key in a map in Kotlin using the putIfAbsent method, which allows us to modify the value only if the key does not already exist.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.putIfAbsent
method to conditionally update the value for a specific key in the map. The putIfAbsent
method takes the key and the new value to be assigned, only if the key does not already exist.println
.fun main() {
// Declare and initialize a mutable map
val myMap = mutableMapOf(
"one" to 1,
"two" to 2,
"three" to 3
)
// Update the value conditionally using putIfAbsent method
myMap.putIfAbsent("two", 22)
// Print the updated map
for ((key, value) in myMap) {
println("$key: $value")
}
}
one: 1 two: 2 three: 3
In this tutorial, we learned How to Update the Value for a Key in a Map in Kotlin language with well detailed examples.