Scala Sets
A set is a collection that stores each value only once. A value that appears more than once in the creation code is stored a single time.
Duplicates disappear when a set is created
The number 2 is written twice in the creation code below. The size of 3 proves only one copy was kept.
@main def main(): Unit =
val numbers = Set(1, 2, 2, 3)
println(numbers.size)
println(numbers.contains(2))
println(numbers.contains(9))Adding with + returns a new set
The + operator builds a new set with one extra value. The two sizes prove the original set stayed smaller.
@main def main(): Unit =
val letters = Set("a", "b")
val bigger = letters + "c"
println(bigger.size)
println(bigger.contains("c"))
println(letters.size)A sorted list copy shows every value in order
Turning a set into a list and sorting it gives a safe order to print. The values appear from smallest to largest.
@main def main(): Unit =
val numbers = Set(30, 10, 20)
println(numbers.toList.sorted)
println(numbers.size)Example
@main def main(): Unit =
val tags = Set("red", "blue", "red", "green")
val withGold = tags + "gold"
println(tags.size)
println(withGold.size)
println(withGold.contains("gold"))
println(withGold.toList.sorted)Key points
- Creation: Set(1, 2, 3) creates a set that holds the three numbers.
- Duplicates: A set removes repeated values automatically when it is created.
- Checking: s.contains(2) gives true when 2 is one of the values in the set.
- Size: s.size gives how many different values the set holds.
- Adding: s + 4 returns a new set that also holds 4.
- Sorted copy: s.toList.sorted returns the values of the set as a sorted list.
In this example, the program creates a set of tags where red is written twice, so the size is 3 and not 4. It adds gold to make a new set of size 4, checks that the new set contains gold, and prints a sorted list copy of the new set.
Note
A set does not promise an order for its values, so this course never prints a set directly.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
What is Set(4, 4, 5, 6).size?