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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.