sachsure
sachsure

Reputation: 888

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")

Upvotes: 5

Views: 3540

Answers (1)

miensol
miensol

Reputation: 41688

You have at least 2 options:

  • use computeIfAbsent:

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

    ss.getOrPut("new_key", ::mutableListOf) += "NEW"
    

Upvotes: 12

Related Questions