Scala Collections Maps Tutorial

4/12/2025

#Scala Collections Maps Turial

Go Back

Scala Collections Maps Tutorial

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.

#Scala Collections Maps Turial

What is a Map in Scala?

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.

Creating Maps

Immutable Map

val capitals = Map("France" -> "Paris", "Japan" -> "Tokyo")

Mutable Map

import scala.collection.mutable
val scores = mutable.Map("Alice" -> 90, "Bob" -> 85)

Empty Map

val emptyMap = Map.empty[String, Int]

Accessing Elements

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")

Adding and Updating Elements

Immutable Map

Returns a new Map:

val updated = capitals + ("Germany" -> "Berlin")

Mutable Map

Modifies the map in place:

scores("Charlie") = 88
scores += ("Dave" -> 92)

Removing Elements

Immutable

val newMap = capitals - "Japan"

Mutable

scores -= "Bob"

Iterating Over Maps

for ((country, city) <- capitals) {
  println(s"Capital of $country is $city")
}

Common Map Operations

  • 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"))

Working with Default Values

val safeMap = capitals.withDefaultValue("Unknown")
safeMap("USA") // Returns "Unknown"

Sorting Maps

While Maps are unordered by default, you can sort them:

val sorted = scala.collection.immutable.SortedMap("c" -> 3, "a" -> 1, "b" -> 2)

Nested Maps

Maps can also be nested:

val students = Map(
  "Alice" -> Map("Math" -> 90, "Science" -> 85),
  "Bob" -> Map("Math" -> 88, "Science" -> 92)
)

Conclusion

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.