Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 37 ยท Collections

Sets and Maps

Learn Scala Set and Map: creating, adding and removing elements, safe lookup with get and getOrElse, iterating, grouping, counting words, and mutable vs immutable versions.

A Set holds unique elements. A Map holds key-value pairs with unique keys. Both are everywhere in real programs: de-duplicating tags, counting words, caching results, looking up configuration. In Scala both come in immutable and mutable flavours, and the immutable ones are the default. This lesson shows how to create, query and update them, and how to avoid the classic "missing key" crash. The Scala is read-only; Java and Kotlin demos run live.

Sets

SCALA
val tags = Set("scala", "jvm", "fp", "scala")
// Set(scala, jvm, fp): the duplicate is dropped

tags.contains("fp")        // true
tags("fp")                 // true: a Set is also a function A => Boolean
tags.size                  // 3
tags + "sbt"               // Set(scala, jvm, fp, sbt): new set
tags - "jvm"               // Set(scala, fp)
tags ++ Set("jvm", "zio")  // adds only the new ones

Immutable operations return new sets. For small sets (up to four elements) Scala uses special compact classes; larger ones use a hash trie. Iteration order is unspecified for a Set (except LinkedHashSet/SortedSet), so do not rely on it.

Set algebra:

SCALA
val a = Set(1, 2, 3, 4)
val b = Set(3, 4, 5)
a & b          // Set(3, 4): intersection (also a.intersect(b))
a | b          // Set(1, 2, 3, 4, 5): union
a &~ b         // Set(1, 2): difference (also a.diff(b))
Set(1, 2).subsetOf(a)  // true

For ordered elements use SortedSet:

SCALA
import scala.collection.immutable.SortedSet
SortedSet(5, 1, 3)    // TreeSet(1, 3, 5)

Kotlin's sets work the same way, and can be run:

Kotlin Set operations (Kotlin comparison)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Maps

A map associates each key with one value:

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

"France" -> "Paris" is just a way of writing the tuple ("France", "Paris").

Looking up values

SCALA
capitals("Japan")                 // "Tokyo"
capitals("Chile")                 // throws NoSuchElementException
capitals.get("Chile")             // None
capitals.get("Peru")              // Some("Lima")
capitals.getOrElse("Chile", "?")  // "?"
capitals.contains("Peru")         // true
capitals.keys                     // France, Japan, Peru
capitals.values                   // Paris, Tokyo, Lima

Use get (which returns an Option) or getOrElse whenever a key might be missing. Direct capitals("Chile") is fine only when you are sure the key exists. A map can also have a default:

SCALA
val counts = Map("a" -> 1).withDefaultValue(0)
counts("zzz")      // 0

Updating an immutable map

SCALA
val m1 = capitals + ("Italy" -> "Rome")   // adds
val m2 = m1.updated("Japan", "Kyoto")     // replaces (new map)
val m3 = m2 - "Peru"                      // removes
val m4 = capitals ++ Map("Spain" -> "Madrid", "Peru" -> "Cusco")

None of these change capitals. If you keep the result in a var, you get the effect of mutation with immutable values:

SCALA
var stock = Map("apple" -> 3)
stock = stock.updated("apple", stock("apple") + 2)   // Map(apple -> 5)

Iterating

SCALA
for (country, city) <- capitals do
  println(s"$country: $city")

capitals.foreach { case (country, city) => println(s"$city is in $country") }
capitals.map { case (c, city) => c -> city.toUpperCase }
capitals.filter { case (_, city) => city.startsWith("T") }
capitals.keySet            // Set(France, Japan, Peru)
capitals.toList            // List((France,Paris), ...)

Mutable collections

SCALA
import scala.collection.mutable

val visited = mutable.Set[String]()
visited += "home"
visited += "about"
visited.contains("home")     // true

val scores = mutable.Map[String, Int]()
scores("ann") = 10           // add or replace
scores("bob") = 7
scores("ann") += 5           // 15
scores.getOrElseUpdate("cy", 0)   // adds cy -> 0 if missing
scores.remove("bob")

Use mutable maps for performance-sensitive counting loops or caches that stay inside one method, and keep them out of public APIs.

Counting words: the classic

SCALA
val text = "to be or not to be"
val counts = text.split(" ").toList
  .groupBy(identity)
  .map { case (word, ws) => word -> ws.size }
// Map(to -> 2, be -> 2, or -> 1, not -> 1)

groupBy(identity) produces Map[String, List[String]], then we replace each list with its size. A shorter version uses groupMapReduce:

SCALA
text.split(" ").groupMapReduce(identity)(_ => 1)(_ + _)

Java's HashMap and merge do the same job, runnable here:

Java Word counts (Java comparison)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Output: {be=2, not=1, or=1, to=2} (a TreeMap sorts the keys, a Scala Map does not promise any order for large maps, so sort before printing when order matters, for example counts.toList.sortBy(_._1)).

Choosing Set and Map variants

Type Behaviour
Set, Map (immutable) default; hash-based; unordered
SortedSet, SortedMap ordered by key, TreeSet/TreeMap
ListMap remembers insertion order, linear lookup, good for small maps
mutable.Set, mutable.Map change in place
mutable.LinkedHashMap insertion order, mutable

Common mistakes

  • Using map(key) when the key may be missing. Prefer get or getOrElse.
  • Assuming a Set or Map keeps insertion order beyond four elements.
  • Using a mutable object as a key and then changing it, so the lookup fails.
  • Forgetting that + on a Map expects a pair: m + ("k" -> 1), with the inner parentheses.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does Set(1, 2, 2, 3).size give?

    A set stores each element once, so the duplicate 2 is dropped.
  2. 2. What does capitals.get("Chile") return when the key is absent?

    get returns an Option: Some(value) when the key exists and None when it does not.
  3. 3. How do you add or replace a key in an immutable Map m?

    Immutable maps never change. updated and + return a new map.
  4. 4. Which operator computes the intersection of two sets a and b?

    & is intersection, | is union and &~ is difference.

Summary

  • Set stores unique values; Map stores unique keys with values; both are immutable by default.
  • Use get, getOrElse and contains for safe lookup; +, -, updated to make new versions.
  • Set algebra uses &, |, &~; iteration order is unspecified unless you use a sorted or linked variant.
  • scala.collection.mutable has Set and Map for in-place changes.
  • groupBy and groupMapReduce turn sequences into maps, which is the basis of counting and grouping.

Next: Transforming Collections