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!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.