Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kotlin adding pair to map when value is a list

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")
like image 265
sachsure Avatar asked Dec 24 '22 09:12

sachsure


1 Answers

You have at least 2 options:

  • use computeIfAbsent:

    ss.computeIfAbsent("new_key") { mutableListOf() } += "NEW"
    
  • use getOrPut:

    ss.getOrPut("new_key", ::mutableListOf) += "NEW"
    
like image 75
miensol Avatar answered Dec 28 '22 08:12

miensol