Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is equivalent function of Map.compute in scala.collection.mutable.Map

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.

like image 611
Rajkumar Natarajan Avatar asked Jun 28 '18 18:06

Rajkumar Natarajan


2 Answers

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)
like image 139
Arnon Rotem-Gal-Oz Avatar answered Nov 14 '22 20:11

Arnon Rotem-Gal-Oz


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.

like image 24
fikovnik Avatar answered Nov 14 '22 21:11

fikovnik