Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Map

A Map is a collection of key-value pairs, where each key is unique. Maps can be either mutable or immutable, but by default, Scala uses immutable maps.

Creating Maps

You can create a Map using the Map companion object.

val fruitPrices = Map("apple" -> 1.0, "banana" -> 0.5, "cherry" -> 2.0)
val numbers = Map(1 -> "one", 2 -> "two", 3 -> "three")

Basic Operations on Maps

Accessing Elements

You can access the value associated with a key using the apply method, which is called using parentheses.

val fruitPrices = Map("apple" -> 1.0, "banana" -> 0.5, "cherry" -> 2.0)

println(fruitPrices("apple"))  // 1.0
println(fruitPrices("banana")) // 0.5

If the key does not exist, apply throws an exception. To avoid this, you can use the get method, which returns an Option.

println(fruitPrices.get("apple"))  // Some(1.0)
println(fruitPrices.get("orange")) // None

Adding and Removing Elements

  • Add: Use the + operator to add a key-value pair.
  • Remove: Use the - operator to remove a key-value pair.
val fruitPrices = Map("apple" -> 1.0, "banana" -> 0.5)
val newFruitPrices = fruitPrices + ("cherry" -> 2.0)
println(newFruitPrices) // Map(apple -> 1.0, banana -> 0.5, cherry -> 2.0)

val lessFruitPrices = newFruitPrices - "banana"
println(lessFruitPrices) // Map(apple -> 1.0, cherry -> 2.0)

For mutable maps, you can modify the map in place.

import scala.collection.mutable

val fruitPrices = mutable.Map("apple" -> 1.0, "banana" -> 0.5)
fruitPrices += ("cherry" -> 2.0)
println(fruitPrices) // Map(apple -> 1.0, banana -> 0.5, cherry -> 2.0)

fruitPrices -= "banana"
println(fruitPrices) // Map(apple -> 1.0, cherry -> 2.0)

Common Map Methods

Mapping

The map method transforms each key-value pair in the map.

val fruitPrices = Map("apple" -> 1.0, "banana" -> 0.5, "cherry" -> 2.0)
val discountedPrices = fruitPrices.map { case (fruit, price) => (fruit, price * 0.9) }
println(discountedPrices) // Map(apple -> 0.9, banana -> 0.45, cherry -> 1.8)

Filtering

The filter method selects key-value pairs that satisfy a predicate.

val fruitPrices = Map("apple" -> 1.0, "banana" -> 0.5, "cherry" -> 2.0)
val expensiveFruits = fruitPrices.filter { case (fruit, price) => price > 1.0 }
println(expensiveFruits) // Map(cherry -> 2.0)

Iterating

You can iterate over key-value pairs in a map using a for loop or the foreach method.

val fruitPrices = Map("apple" -> 1.0, "banana" -> 0.5, "cherry" -> 2.0)

for ((fruit, price) <- fruitPrices) {
  println(s"The price of $fruit is $$ $price")
}

fruitPrices.foreach { case (fruit, price) => 
  println(s"The price of $fruit is $$ $price")
}

Immutable vs Mutable Maps

Immutable maps cannot be changed after they are created, while mutable maps can be updated in place.

Immutable Map

val fruitPrices = Map("apple" -> 1.0, "banana" -> 0.5)
val newFruitPrices = fruitPrices + ("cherry" -> 2.0)
println(fruitPrices)     // Map(apple -> 1.0, banana -> 0.5)
println(newFruitPrices)  // Map(apple -> 1.0, banana -> 0.5, cherry -> 2.0)

Mutable Map

import scala.collection.mutable

val fruitPrices = mutable.Map("apple" -> 1.0, "banana" -> 0.5)
fruitPrices += ("cherry" -> 2.0)
println(fruitPrices) // Map(apple -> 1.0, banana -> 0.5, cherry -> 2.0)

Advanced Map Operations

Merging Maps

You can merge two maps using the ++ operator or the ++= method for mutable maps.

val map1 = Map(1 -> "one", 2 -> "two")
val map2 = Map(2 -> "two revised", 3 -> "three")

val mergedMap = map1 ++ map2
println(mergedMap) // Map(1 -> one, 2 -> two revised, 3 -> three)

For mutable maps:

val map1 = mutable.Map(1 -> "one", 2 -> "two")
val map2 = Map(2 -> "two revised", 3 -> "three")

map1 ++= map2
println(map1) // Map(1 -> one, 2 -> two revised, 3 -> three)

Grouping

The groupBy method groups elements of a collection by a specified key function.

val words = List("apple", "banana", "cherry", "date", "apricot")
val groupedByFirstLetter = words.groupBy(_.head)
println(groupedByFirstLetter) 
// Map(a -> List(apple, apricot), b -> List(banana), c -> List(cherry), d -> List(date))

Transforming Keys and Values

You can transform the keys and values of a map using the mapKeys and mapValues methods (these methods are available in more recent versions of Scala).

val fruitPrices = Map("apple" -> 1.0, "banana" -> 0.5)

// Transform keys
val upperCaseKeys = fruitPrices.map { case (fruit, price) => (fruit.toUpperCase, price) }
println(upperCaseKeys) // Map(APPLE -> 1.0, BANANA -> 0.5)

// Transform values
val discountedPrices = fruitPrices.mapValues(price => price * 0.9)
println(discountedPrices) // Map(apple -> 0.9, banana -> 0.45)

Conversions

You can convert maps to other collection types, such as lists or arrays.

val fruitPrices = Map("apple" -> 1.0, "banana" -> 0.5)

val fruitList = fruitPrices.toList
println(fruitList) // List((apple,1.0), (banana,0.5))

val fruitArray = fruitPrices.toArray
println(fruitArray.mkString(", ")) // (apple,1.0), (banana,0.5)