Home »
Scala
Convert immutable Map to mutable Map in Scala
Scala | Converting from immutable Map to mutable Map: Here, we are going to learn how to convert immutable Map to mutable Map in Scala?
Submitted by Shivang Yadav, on May 28, 2020
Map: Scala Map is a collection that stores elements as key-value pairs. The key value for a map is always unique and is used to access the specific pair in the map.
Immutable Map: is a map in which the number of elements cannot be altered also the values cannot be changed. It is defined in scala.collection.immutable.Map
Mutable Map: is an editable map, i.e. the number of elements and values can be changed after the creation of the map. It is defined in scala.collection.mutable.Map
Immutable Map to Mutable Map Conversion in Scala
This method seems a little bit different but is a valid way to get elements of an immutable map to a mutable Map. This is by using the properties of a mutable map i.e. adding elements to the map.
Program:
object MyObject {
def main(args: Array[String]) {
val immutableMap = Map (1 -> "scala" , 2 -> "Python" , 3 -> "JavaScript")
println("Immutalbe Map : " + immutableMap)
val mutableMap = collection.mutable.Map[Int, String]()
mutableMap ++= immutableMap
println("Mutalbe Map : " + mutableMap)
}
}
Output:
Immutalbe Map : Map(1 -> scala, 2 -> Python, 3 -> JavaScript)
Mutalbe Map : HashMap(1 -> scala, 2 -> Python, 3 -> JavaScript)
Explanation:
In the above code, we have discussed how to convert immutable Map to mutable Map in Scala? We have created an immutable map named immutableMap. Then to convert this to a mutable map, we have created an empty mutable map named mutableMap to this map we have added values of the immutableMap using ++ operator.