How can I convert immutable.Map
to mutable.Map
in Scala so I can update the values in Map
?
You can use myMap. toMap to convert an a mutable map into immutable in Scala 2.8 and later versions.
To create a mutable map, either use an import statement to bring it into scope, or specify the full path to the scala. collection. mutable. Map class when you create an instance.
Maps are classified into two types: mutable and immutable. By default Scala uses immutable Map. In order to use mutable Map, we must import scala.
The cleanest way would be to use the mutable.Map
varargs factory. Unlike the ++
approach, this uses the CanBuildFrom
mechanism, and so has the potential to be more efficient if library code was written to take advantage of this:
val m = collection.immutable.Map(1->"one",2->"Two") val n = collection.mutable.Map(m.toSeq: _*)
This works because a Map
can also be viewed as a sequence of Pairs.
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