Scala Maps

A Map is a collection of key-value pairs where each key is unique. You use a Map when you want to look something up quickly by a name or identifier — like a dictionary, a phone book, or a configuration table. Keys can be any type, and values can be any type.

Creating a Map

val capitals = Map("India" -> "New Delhi", "Japan" -> "Tokyo", "France" -> "Paris")
val ages = Map("Alice" -> 30, "Bob" -> 25, "Carol" -> 35)
val empty = Map.empty[String, Int]

Key      →   Value
────────     ─────────
"India"  →   "New Delhi"
"Japan"  →   "Tokyo"
"France" →   "Paris"

Accessing Values

val prices = Map("Apple" -> 50, "Banana" -> 20, "Cherry" -> 120)

// Direct access — throws exception if key missing
println(prices("Apple"))     // 50

// Safe access — returns Option
println(prices.get("Apple"))    // Some(50)
println(prices.get("Durian"))   // None

// With a default
println(prices.getOrElse("Mango", 0))    // 0  (not in map)
println(prices.getOrElse("Apple", 0))    // 50

Adding and Updating

val base = Map("a" -> 1, "b" -> 2)

val added   = base + ("c" -> 3)           // adds new key
val updated = base + ("a" -> 99)          // updates existing key
val removed = base - "b"                  // removes key "b"
val merged  = base ++ Map("c" -> 3, "d" -> 4)

println(base)     // Map(a -> 1, b -> 2)  — original unchanged
println(added)    // Map(a -> 1, b -> 2, c -> 3)
println(updated)  // Map(a -> 99, b -> 2)

Iterating Over a Map

val inventory = Map("Pen" -> 500, "Notebook" -> 200, "Pencil" -> 800)

// Destructuring key-value pairs
for (item, qty) <- inventory do
  println(s"$item: $qty units")

// Keys and values separately
inventory.keys.foreach(println)
inventory.values.toList.sum   // total inventory count = 1500

Map Operations

val scores = Map("Alice" -> 92, "Bob" -> 78, "Carol" -> 85, "Dave" -> 61)

// Transform values
val doubled = scores.map { (name, score) => name -> score * 2 }

// Filter entries
val highScorers = scores.filter { (_, score) => score >= 80 }
println(highScorers)   // Map(Alice -> 92, Carol -> 85)

// Get all keys
val names = scores.keySet     // Set(Alice, Bob, Carol, Dave)

// Get all values as a list
val allScores = scores.values.toList   // List(92, 78, 85, 61)

// Check if key exists
scores.contains("Alice")   // true
scores.contains("Eve")     // false

groupBy — Building Maps from Lists

val words = List("apple", "ant", "bear", "banana", "cat", "cherry")

val byFirstLetter = words.groupBy(_.head)
// Map(a -> List(apple, ant), b -> List(bear, banana), c -> List(cat, cherry))

byFirstLetter.toList.sortBy(_._1).foreach { (letter, words) =>
  println(s"$letter: ${words.mkString(", ")}")
}
// a: apple, ant
// b: bear, banana
// c: cat, cherry

Mutable Map

import scala.collection.mutable

val stock = mutable.Map("Apple" -> 100, "Banana" -> 50)
stock("Apple") = 80    // update
stock("Cherry") = 200  // add new
stock.remove("Banana") // delete

println(stock)   // Map(Apple -> 80, Cherry -> 200)

Practical: Word Frequency Counter

val text = "to be or not to be that is the question to be"
val words = text.split(" ")

val frequency = words.groupBy(identity).map { (word, occurrences) =>
  word -> occurrences.length
}

frequency.toList.sortBy(-_._2).take(5).foreach { (word, count) =>
  println(s"'$word': $count times")
}
// 'be': 3 times
// 'to': 3 times
// 'or': 1 times
// 'not': 1 times
// 'that': 1 times

Leave a Comment

Your email address will not be published. Required fields are marked *