Home »
Scala
How to create a map in Scala?
By IncludeHelp Last updated : November 15, 2024
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", ...)
Example to Create a Mutable Map
object myObject {
def main(args: Array[String]): Unit = {
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
object myObject {
def main(args: Array[String]): Unit = {
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)
Another Example
You can create an empty mutable map initially and then add elements to it, using +=.
object myObject {
def main(args: Array[String]): Unit = {
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)