Scala Sets

A Set is a collection of unique values with no duplicates. If you add the same value twice, the Set keeps it only once. Sets do not guarantee order (unless you use a sorted set). They are ideal when you need to test membership, remove duplicates, or compute unions and intersections.

Creating Sets

val fruits = Set("Apple", "Banana", "Cherry")
val numbers = Set(1, 2, 3, 4, 5)
val withDupes = Set(1, 2, 2, 3, 3, 3)   // Set(1, 2, 3)  — duplicates removed
val empty = Set.empty[String]

Adding and Removing

val base = Set("Red", "Green", "Blue")

val added = base + "Yellow"   // Set(Red, Green, Blue, Yellow)
val removed = base - "Green"  // Set(Red, Blue)
val addMultiple = base ++ Set("White", "Black")

println(base)        // original unchanged
println(added)       // new Set with Yellow

Set Operations

val a = Set(1, 2, 3, 4, 5)
val b = Set(3, 4, 5, 6, 7)

val union        = a | b    // Set(1,2,3,4,5,6,7) — all elements
val intersection = a & b    // Set(3,4,5)          — common elements
val difference   = a &~ b   // Set(1,2)            — in a but not b
val diffBA       = b &~ a   // Set(6,7)            — in b but not a

    a: 1  2  3  4  5
    b:          3  4  5  6  7

Union:        1  2  3  4  5  6  7
Intersection:          3  4  5
a - b:        1  2
b - a:                       6  7

Membership Testing

val validCodes = Set("USD", "EUR", "GBP", "INR", "JPY")

println(validCodes.contains("INR"))  // true
println(validCodes("EUR"))           // true  (shorthand for contains)
println(validCodes("XYZ"))           // false

def processPayment(currency: String): String =
  if validCodes(currency) then s"Processing $currency payment"
  else s"Unsupported currency: $currency"

println(processPayment("EUR"))   // Processing EUR payment
println(processPayment("BTC"))   // Unsupported currency: BTC

Sorted Set

import scala.collection.immutable.SortedSet

val sorted = SortedSet(5, 3, 8, 1, 9, 2, 7)
println(sorted)   // TreeSet(1, 2, 3, 5, 7, 8, 9)  — always sorted

val wordSet = SortedSet("banana", "apple", "cherry", "date")
println(wordSet)  // TreeSet(apple, banana, cherry, date)

Mutable Set

import scala.collection.mutable

val mutableSet = mutable.Set(1, 2, 3)
mutableSet += 4        // add
mutableSet -= 2        // remove
mutableSet ++= Set(5, 6)  // add multiple
println(mutableSet)   // Set(1, 3, 4, 5, 6)

Practical: Removing Duplicates

val tags = List("scala", "functional", "scala", "jvm", "functional", "types")
val uniqueTags = tags.toSet
println(uniqueTags)   // Set(scala, functional, jvm, types)

val pageVisits = List("home", "about", "home", "products", "about", "home")
val uniquePages = pageVisits.distinct.length
println(s"Unique pages visited: $uniquePages")   // 3

Leave a Comment

Your email address will not be published. Required fields are marked *