Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: If HashMap does not contain a certain value, then create key

Tags:

kotlin

I have the following HashMap:

val myHashMap: HashMap<key, ValueClass>

where:

data class ValueClass(
    var a: Long = 0,
    var b: Long = 0
)

I'd like to use the myHashMap as follows: if myHashMap, does not contain the key x, create a new ValueClass and insert it into myHashMap, then myHashMap[x].a = newValue.

What is the cleanest way to do so? In Java, I would have had:

    if (!myHashMap.containsKey("x"))
    {
        map.put("x", new ValueClass());
    }

    map.get("x").a = newValue;
like image 474
Hossein Avatar asked Nov 24 '25 04:11

Hossein


2 Answers

Use MutableMap#getOrPut

myMap.getOrPut("key") { "default_value" }
like image 111
Laurence Avatar answered Nov 26 '25 19:11

Laurence


Another alternative:

val foo = map["x"] ?: ValueClass().also { map["x"] = it }

foo.x = newValue
like image 42
jfawkes Avatar answered Nov 26 '25 21:11

jfawkes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!