I know this is basic but can I do this in a shorter way:
val ss = mutableMapOf<String, MutableList<String>>()
if(ss["new_key"] != null){
ss["new_key"]!!.add("NEW")
}
else{
ss["new_key"] = mutableListOf("OLD")
}
This basically checks if the key exists in the map
if it does an element is appended to the list(value) otherwise a new key-value pair is created
Can't I create a new key on the go? like this:
ss["new_key"].add("OLD")
ss["new_key"].add("NEW")
You have at least 2 options:
use computeIfAbsent
:
ss.computeIfAbsent("new_key") { mutableListOf() } += "NEW"
use getOrPut
:
ss.getOrPut("new_key", ::mutableListOf) += "NEW"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With