Scala Sets
A Set is a collection with no duplicates. Adding an element that is already present changes nothing. Sets are ideal for membership checks ("have we seen this before?") and for set algebra such as union and intersection. The default Set is immutable.
Creating a set
@main def run(): Unit =
val tags = Set("scala", "jvm", "fp", "scala")
println(tags)
println(tags.size)
println(tags.contains("fp"))
println(tags("java")) // same as contains
val fromList = List(3, 1, 3, 2, 1).toSet
println(fromList)Set(scala, jvm, fp)
3
true
false
Set(3, 1, 2)
The duplicate "scala" was silently dropped.
Note: A
Setmakes no promise about order. Small immutable sets (up to four elements) happen to keep insertion order, but larger ones are hash-based and look shuffled. When order matters, sort the result (toList.sorted) or use aSortedSet.
Adding and removing
@main def run(): Unit =
val base = Set(1, 2, 3)
println(base + 4)
println(base + 2)
println(base - 1)
println(base ++ List(5, 6))
println(base -- Set(1, 2))
println(s"base unchanged: $base")Set(1, 2, 3, 4)
Set(1, 2, 3)
Set(2, 3)
HashSet(5, 1, 6, 2, 3)
Set(3)
base unchanged: Set(1, 2, 3)
The fourth result has five elements, so it became a HashSet and its order is no longer the insertion order — exactly what the note above warned about.
Set algebra
| Operation | Method | Symbol |
|---|---|---|
| union (in either) | a.union(b) |
a | b |
| intersection (in both) | a.intersect(b) |
a & b |
difference (in a, not b) |
a.diff(b) |
a &~ b |
| subset test | a.subsetOf(b) |
— |
@main def run(): Unit =
val alice = Set("chess", "hiking", "jazz")
val bob = Set("jazz", "cooking", "chess")
println((alice & bob).toList.sorted)
println((alice | bob).toList.sorted)
println((alice &~ bob).toList.sorted)
println(Set("jazz").subsetOf(alice))List(chess, jazz)
List(chess, cooking, hiking, jazz)
List(hiking)
true
Sorting before printing makes the output stable no matter how the set stores its elements.
SortedSet
SortedSet (a TreeSet under the hood) keeps its elements in order at all times.
import scala.collection.immutable.SortedSet
@main def run(): Unit =
val visitors = SortedSet("mia", "ari", "zed", "kim", "ben", "ari")
println(visitors)
println(visitors.head)
println(visitors.rangeFrom("k"))
val byLength = SortedSet(30, 4, 17, 9)(using Ordering.Int.reverse)
println(byLength)TreeSet(ari, ben, kim, mia, zed)
ari
TreeSet(kim, mia, zed)
TreeSet(30, 17, 9, 4)
Practical example: finding duplicates
Sets make "seen before?" checks fast and simple.
@main def run(): Unit =
val emails = List("a@x.io", "b@x.io", "a@x.io", "c@x.io", "b@x.io")
val (_, duplicates) = emails.foldLeft((Set.empty[String], List.empty[String])) {
case ((seen, dups), e) =>
if seen(e) then (seen, dups :+ e) else (seen + e, dups)
}
println(s"duplicates: $duplicates")
println(s"unique count: ${emails.toSet.size}")duplicates: List(a@x.io, b@x.io)
unique count: 3
Mutable sets
scala.collection.mutable.Set can be changed in place with += and -=:
import scala.collection.mutable
val visited = mutable.Set[Int]()
visited += 4
visited += 4
visited.size // 1Prefer the immutable version unless you have a measurable reason to mutate.
Test yourself
What is Set(1, 2, 2, 3).size?
- 4
- 3
- 2
- It throws
Which operator gives the intersection of two sets?
|&++--
How can you make printed set contents appear in a predictable order?
- Sets are always sorted
- Convert with
toList.sortedor use aSortedSet - Call
.reverse - Use
Set.ordered