How to Convert Hashmap to Map in Scala?

Scala | Converting Hashmap to Map: Here, we will learn about the method to convert Java map (hashmap) to the Scala map (map).
Submitted by Shivang Yadav, on June 24, 2020

Let's first understand what are maps and hashmaps?

map in Scala is a collection that stores its elements as key-value pairs, like a dictionary.

Example:

Map( 1 -> Scala, 2 -> Python, 3 -> Javascript) 

hashmap is a collection based on maps and hashes. It stores key-value pairs.

Example:

HashMap( 1 -> Scala, 2 -> Python, 3 -> Javascript) 

Converting HashMap to Map

In Scala, we can convert a hashmap to a map using the tomap method.

Syntax:

Map = HashMap.toMap

Scala program to convert hashmap to map

import scala.collection.mutable.HashMap ;

object MyClass {
    def main(args: Array[String]) {
        val hashMap = HashMap(1->"Scala", 2->"Python", 3->"JavaScript")
        println("HashMap: " + hashMap)
        val map = hashMap.toMap
        println("Map: " + map)
    }
}

Output:

HashMap: HashMap(1 -> Scala, 2 -> Python, 3 -> JavaScript)
Map: Map(1 -> Scala, 2 -> Python, 3 -> JavaScript)

Explanation:

In the above code, we have created a HashMap and then convert it to a Map using the toMap method.






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.