Home » Scala language

How to create a map in Scala?

Scala | Creating a map: Here, we are going to learn about the different methods that are used to create a map in the Scala programming language.
Submitted by Shivang Yadav, on April 14, 2020

Scala | Creating a map

A map is a special type of collection that stores data in key-value pairs. These are also known as hashtables. The keys that are used to extract the value should be unique.

You can create a mutable as well as an immutable map in Scala. The immutable version is inbuilt but mutable map creation needs explicit import.

Syntax:

    val mapName = Map("key1"->"value1", ...)

Now let's see how to create a mutable map in Scala?

object myObject {
    def main(args: Array[String]) {
        val cars = Map("Honda" -> "Amaze", "Suzuki" -> "Baleno", "Audi" -> "R8", "BMW" -> "Z4")
        println(cars)
    }
}

Output

Map(Honda -> Amaze, Suzuki -> Baleno, Audi -> R8, BMW -> Z4)

Generally, the above way of creating a map is used. But sometimes to make the code more clear, another way of declaring maps is used.

val cars = Map( 
("Honda" -> "Amaze"), 
("Suzuki" -> "Baleno"), 
("Audi" -> "R8"), 
("BMW" -> "Z4")
)

This method can also be used as the maps are created as a key->value pair, so pair are enclosed together in the brackets. Both styles are valid and use can use any.

Scala mutable maps

Mutable maps are required when we need to add more elements to the map after declaring it.

For creating a mutable map use scala.collection.mutable.Map or import the same for creating an immutable map.

Syntax:

    var map_name = collection.mutable.Map( 
        "key1"->"value1", 
        "key2"->"value2", ...
        )

Program to create a mutable map in Scala

object myObject {
    
    def main(args: Array[String]) {
        val cars = collection.mutable.Map(
            "Honda" -> "Amaze", 
            "Suzuki" -> "Baleno", 
            "Audi" -> "R8"
            )
            
        println(cars)
        
        println("Adding new elements to the map")
        cars += ("BMW" -> "Z4")
        
        println(cars)
    }
}

Output:

HashMap(Audi -> R8, Honda -> Amaze, Suzuki -> Baleno)
Adding new elements to the map
HashMap(BMW -> Z4, Audi -> R8, Honda -> Amaze, Suzuki -> Baleno)

You can create an empty mutable map initially and then add elements to it, using +=.

object myObject {
    
    def main(args: Array[String]) {
        val cars = collection.mutable.Map[String, String]()
        println(cars)
        println("Adding new elements to the map")
        cars += ("BMW" -> "Z4")
        println(cars)
    }
}

Output:

HashMap()
Adding new elements to the map
HashMap(BMW -> Z4)



Comments and Discussions!

Load comments ↻






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