Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Set

A Set is a collection of unique elements. The Set trait has two subtraits, scala.collection.immutable.Set and scala.collection.mutable.Set. By default, Scala uses immutable sets.

Creating Sets

You can create a Set using the Set companion object.

val fruit = Set("apple", "banana", "cherry")
val numbers = Set(1, 2, 3, 4, 5)

Basic Operations on Sets

Adding and Removing Elements

  • Add: Use the + operator to add an element.
  • Remove: Use the - operator to remove an element.
val fruit = Set("apple", "banana", "cherry")

val moreFruit = fruit + "date"
println(moreFruit) // Set(apple, banana, cherry, date)

val lessFruit = fruit - "banana"
println(lessFruit) // Set(apple, cherry)

For mutable sets, you can modify the set in place.

import scala.collection.mutable

val fruit = mutable.Set("apple", "banana", "cherry")

fruit += "date"
println(fruit) // Set(apple, banana, cherry, date)

fruit -= "banana"
println(fruit) // Set(apple, cherry, date)

Checking Membership

Use the contains method or the apply method (which is called using parentheses).

val fruit = Set("apple", "banana", "cherry")

println(fruit.contains("banana")) // true
println(fruit("banana"))          // true
println(fruit("date"))            // false

Common Set Methods

Union, Intersection, and Difference

  • Union: Combines two sets, including all elements from both sets.
  • Intersection: Returns elements that are present in both sets.
  • Difference: Returns elements that are present in the first set but not in the second.
val set1 = Set(1, 2, 3)
val set2 = Set(3, 4, 5)

val unionSet = set1 | set2           // Set(1, 2, 3, 4, 5)
val intersectionSet = set1 & set2    // Set(3)
val differenceSet = set1 &~ set2     // Set(1, 2)

println(unionSet)
println(intersectionSet)
println(differenceSet)

Subsets and Supersets

  • Subset: Checks if a set is a subset of another set.
  • Superset: Checks if a set is a superset of another set.
val set1 = Set(1, 2, 3)
val set2 = Set(1, 2)

println(set2.subsetOf(set1)) // true
println(set1.subsetOf(set2)) // false

Immutable vs Mutable Sets

Immutable sets cannot be changed after they are created, while mutable sets can be updated in place.

Immutable Set

val fruit = Set("apple", "banana", "cherry")
val moreFruit = fruit + "date"
println(fruit)     // Set(apple, banana, cherry)
println(moreFruit) // Set(apple, banana, cherry, date)

Mutable Set

import scala.collection.mutable

val fruit = mutable.Set("apple", "banana", "cherry")
fruit += "date"
println(fruit) // Set(apple, banana, cherry, date)

Conversions

You can convert sets to other collection types, such as lists or arrays.

val numbers = Set(1, 2, 3, 4, 5)

val numberList = numbers.toList
println(numberList) // List(1, 2, 3, 4, 5)

val numberArray = numbers.toArray
println(numberArray.mkString(", ")) // 1, 2, 3, 4, 5