Java has method in java.util.Map called compute which provides a way to update map when the key is present or absent in the map.
Does scala.collection.mutable.Map provides any similar function?
I've checked the documentation Map and HashMap but couldn't find equivalent ones.
you can use update and getOrElse as in
val x= scala.collection.mutable.Map("a"->1,"b"->2)
x.update("c",x.getOrElse("c",1)+41)
x.update("a",x.getOrElse("a",1)+41)
There is getOrElseUpdate defined in mutable.MapLike trait which does exactly what you want:
def getOrElseUpdate(key: K, op: ⇒ V): V
If given key is already in this map, returns associated value. Otherwise, computes value from given expression op, stores with key in map and returns that value.
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