Scala Collections Maps Tutorial
Mutable vs immutable map scala
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.
In Scala, a Map is a collection of key-value pairs that allows fast data retrieval based on keys. Scala supports two types of Maps: immutable and mutable, catering to different programming paradigms and use cases.
By default, Scala favors immutable collections, aligning with functional programming principles. An immutable Map cannot be modified once it is created—any operation like adding or removing elements returns a new Map. This ensures thread safety and predictability in concurrent environments.
On the other hand, a mutable Map allows in-place updates, additions, and removals. It’s part of Scala’s mutable collection library and is more suited for use cases where performance and frequent updates are priorities.
Understanding the differences between mutable and immutable Maps is essential for writing efficient and idiomatic Scala code. In this article, we will explore their syntax, performance characteristics, and best practices for choosing the right one.
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.