To set a default value for a key in a map in Kotlin, you can use the getOrPut method, which inserts the key with a default value if the key does not already exist.
We can set a default value for a key in a map in Kotlin using the getOrPut method, which inserts a key-value pair if the key does not already exist in the map.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.getOrPut
method to set a default value for a key. The getOrPut
method takes the key and a lambda that returns the default value to be inserted if the key is not already present in the map.println
.fun main() {
// Declare and initialize a mutable map
val myMap = mutableMapOf(
"one" to 1,
"two" to 2,
"three" to 3
)
// Set a default value using getOrPut method
myMap.getOrPut("four") { 4 }
// Print the updated map
for ((key, value) in myMap) {
println("$key: $value")
}
}
one: 1 two: 2 three: 3 four: 4
We can set multiple default values for keys in a map in Kotlin using the getOrPut method, which inserts key-value pairs if the keys do not already exist in the map.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.getOrPut
method to set multiple default values for keys. The getOrPut
method takes the key and a lambda that returns the default value to be inserted if the key is not already present in the map.println
.fun main() {
// Declare and initialize a mutable map
val myMap = mutableMapOf(
"one" to 1,
"two" to 2,
"three" to 3
)
// Set multiple default values using getOrPut method
myMap.getOrPut("four") { 4 }
myMap.getOrPut("five") { 5 }
// Print the updated map
for ((key, value) in myMap) {
println("$key: $value")
}
}
one: 1 two: 2 three: 3 four: 4 five: 5
We can set a default value for a key in a map in Kotlin using the getOrPut method, which inserts a key-value pair if the key does not already exist in the map, based on a condition.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.getOrPut
method to set a default value for a key based on a condition. The getOrPut
method takes the key and a lambda that returns the default value to be inserted if the key is not already present in the map.println
.fun main() {
// Declare and initialize a mutable map
val myMap = mutableMapOf(
"one" to 1,
"two" to 2,
"three" to 3
)
// Set a default value conditionally using getOrPut method
myMap.getOrPut("four") { myMap["four"] ?: 4 }
// Print the updated map
for ((key, value) in myMap) {
println("$key: $value")
}
}
one: 1 two: 2 three: 3 four: 4
In this tutorial, we learned How to Set a Default Value for a Key in a Map in Kotlin language with well detailed examples.