Start learning free

LESSON 240 OF 348 · HASH TABLE

Hash Sets in Scala in Scala

Lesson

A Scala Set stores unique values. If the same value is added more than once, it still appears only once.

Creating a Set:

val mySet = Set("b", "c", "c", "d")

// mySet contains b, c, and d

Checking membership:

val exists = mySet.contains("c") // true

Mutable sets:

val mutableSet = scala.collection.mutable.Set("b", "c", "d")
mutableSet += "x"
mutableSet -= "c"

Iterating:

for (value <- mySet) {
    println(value)
}

Assignment
Follow the Coding Tutorial and let's play with sets.


Hint
Use Set(...) for unique values.


STEP 1 OF 6
    Ctrl + Enter to check

    Hash Set in Scala

    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free