Scala Collections Maps Tutorial
#Scala Collections Maps Turial
In Scala, Maps are one of the most widely used collection types, ideal for storing key-value pairs. Whether you're building a lookup table, configuring application settings, or managing a dataset, Maps provide powerful features and performance. In this tutorial, we'll explore everything from the basics of Maps to advanced operations and best practices.
A Map in Scala is a collection of key-value pairs where each key is unique. Scala provides both immutable and mutable versions of Maps, catering to different programming needs.
val immutableMap = Map("a" -> 1, "b" -> 2)
var mutableMap = scala.collection.mutable.Map("x" -> 10, "y" -> 20)
By default, Map
refers to an immutable map. If you need to update contents frequently, use the mutable version explicitly.
val capitals = Map("France" -> "Paris", "Japan" -> "Tokyo")
import scala.collection.mutable
val scores = mutable.Map("Alice" -> 90, "Bob" -> 85)
val emptyMap = Map.empty[String, Int]
You can retrieve values using keys:
val capital = capitals("France") // Returns "Paris"
To avoid exceptions for missing keys, use get
, getOrElse
, or pattern matching:
capitals.get("Germany") // Returns Option[String]
capitals.getOrElse("Germany", "Not Found")
Returns a new Map:
val updated = capitals + ("Germany" -> "Berlin")
Modifies the map in place:
scores("Charlie") = 88
scores += ("Dave" -> 92)
val newMap = capitals - "Japan"
scores -= "Bob"
for ((country, city) <- capitals) {
println(s"Capital of $country is $city")
}
keys: Returns all keys
values: Returns all values
contains(key): Checks if a key exists
map / filter / foreach: Functional transformations
capitals.map { case (k, v) => (k.toUpperCase, v) }
capitals.filter(_._1.startsWith("F"))
val safeMap = capitals.withDefaultValue("Unknown")
safeMap("USA") // Returns "Unknown"
While Maps are unordered by default, you can sort them:
val sorted = scala.collection.immutable.SortedMap("c" -> 3, "a" -> 1, "b" -> 2)
Maps can also be nested:
val students = Map(
"Alice" -> Map("Math" -> 90, "Science" -> 85),
"Bob" -> Map("Math" -> 88, "Science" -> 92)
)
Scala Maps are a versatile and efficient way to manage key-value data. Understanding the differences between mutable and immutable Maps—and knowing how to leverage functional operations—can help you write safer, more expressive code. Whether you're a beginner or a seasoned Scala developer, mastering Maps is a key step in becoming fluent with the language's powerful collection framework.