Collections: Sets in Scala – A Beginner’s Guide

4/12/2025

Scala Set example code

Go Back

Collections: Sets in Scala – A Beginner’s Guide

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.

Scala Set example code

What is a Set?

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")

Creating Sets

Immutable Set

val numbers = Set(10, 20, 30, 40)

Mutable Set

import scala.collection.mutable
val fruits = mutable.Set("apple", "banana")

Empty Set

val empty = Set.empty[Int]

Adding Elements

Immutable

Creates a new Set:

val newSet = numbers + 50

Mutable

Updates in-place:

fruits += "orange"

Removing Elements

Immutable

val smallerSet = numbers - 10

Mutable

fruits -= "banana"

Checking Membership

numbers.contains(20)  // true
fruits.contains("apple")  // true

Set Operations

Union

val setA = Set(1, 2, 3)
val setB = Set(3, 4, 5)
val unionSet = setA union setB  // Set(1, 2, 3, 4, 5)

Intersection

val intersection = setA intersect setB  // Set(3)

Difference

val diff = setA diff setB  // Set(1, 2)

Iterating Over a Set

for (item <- setA) {
  println(item)
}

Converting Between Collections

val list = List(1, 2, 2, 3)
val toSet = list.toSet  // Removes duplicates
val backToList = toSet.toList

Performance and Use Cases

  • 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.

Conclusion

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.