← Back to Scala Course | Chapter 6: Collections Basics | Lesson 5 of 8

Set

In this page:

  1. Set

Set

A Set stores unique elements with no defined order and no duplicates -- adding an element that already exists has no effect. Set(1, 2, 3) creates an immutable set by default; scala.collection.mutable.Set provides a mutable version supporting +=/-=. Sets are ideal for membership tests and removing duplicates from data.

Note: Adding a duplicate value to a Set is silently a no-op -- the set's size never changes for an already-present element.

Example: Set

markup
object Main extends App {
  val ids = Set(1, 2, 3)
  val expanded = ids + 2 + 4 // 2 already exists, ignored

  println(expanded)
  println(expanded.contains(3))
  println(expanded.size)
}
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.