×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

How to Convert Hashmap to Map in Scala?

By IncludeHelp Last updated : November 16, 2024

Map

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

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]): Unit = {
        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.