Collections: Sets in Scala – A Beginner’s Guide
Scala Set example code
Sets are a fundamental part of Scala’s collections framework, designed to store unique elements. Whether you’re checking membership, removing duplicates, or performing set operations like union and intersection, Scala’s Set makes it simple and powerful. This beginner-friendly guide will walk you through the essentials of working with Sets in Scala.
A Set in Scala is a collection that contains no duplicate elements. Like Maps, Sets come in two flavors:
Immutable Sets (default)
Mutable Sets (require explicit import)
val immutableSet = Set(1, 2, 3, 3) // Result: Set(1, 2, 3)
import scala.collection.mutable
val mutableSet = mutable.Set("apple", "banana")
val numbers = Set(10, 20, 30, 40)
import scala.collection.mutable
val fruits = mutable.Set("apple", "banana")
val empty = Set.empty[Int]
Creates a new Set:
val newSet = numbers + 50
Updates in-place:
fruits += "orange"
val smallerSet = numbers - 10
fruits -= "banana"
numbers.contains(20) // true
fruits.contains("apple") // true
val setA = Set(1, 2, 3)
val setB = Set(3, 4, 5)
val unionSet = setA union setB // Set(1, 2, 3, 4, 5)
val intersection = setA intersect setB // Set(3)
val diff = setA diff setB // Set(1, 2)
for (item <- setA) {
println(item)
}
val list = List(1, 2, 2, 3)
val toSet = list.toSet // Removes duplicates
val backToList = toSet.toList
Sets offer fast lookups, usually O(1) for mutable HashSets.
Ideal for tasks like removing duplicates, membership testing, and mathematical operations.
Prefer immutable Sets in functional programming for safer, thread-safe code.
Scala Sets provide a clean and efficient way to manage unique elements in your application. By understanding how to create, manipulate, and apply set operations, you gain a powerful tool in the Scala collections toolkit. Whether you're cleaning data or modeling real-world sets, mastering Sets is a crucial step in your Scala learning journey.