In Scala programs we often need to track unique elements—ones not already encountered. A set allows only distinct elements—it eliminates duplicates.
With special operators, like "++," we combine sets. In the two sets, any duplicate elements will be lost. Scala 3.3 provides the Set type with simple syntax.
This example uses a Set. It adds two elements to the set in the first line. With val
we specify that our "animals" variable cannot be reassigned to something else.
contains()
method returns true or false. It tells us whether the argument exists within the set.object Program { def main(args: Array[String]): Unit = { // Create a Set of two strings. val animals = Set("bird", "fish") println(animals) // See if this string is in the set. if (animals.contains("fish")) { println(true) } // This string is not contained in the set. println(animals.contains("apple")) } }Set(bird, fish) true false
Sets are immutable, so we cannot add or remove single elements of the existing collection. Instead we must create new sets with operators or methods.
object Program { def main(args: Array[String]): Unit = { // Create two sets. val results1 = Set(10, 11, 15) val results2 = Set(2, 3, 15) // Combine the sets. // ... This eliminates duplicate elements. // Ordering of elements is not retained. val results3 = results1 ++ results2 // Display all sets. println(results1) println(results2) println(results3) } }Set(10, 11, 15) Set(2, 3, 15) HashSet(10, 2, 3, 11, 15)
The intersection of two sets is the common elements of both sets. We compute an intersection with intersect()
or an ampersand. Both map to the same function.
object Program { def main(args: Array[String]): Unit = { val codes1 = Set(20, 21, 30) val codes2 = Set(40, 20, 30) // Use intersect to find common elements of two sets. val result1 = codes1.intersect(codes2) println(result1) // Short syntax for intersection. val result2 = codes1 & codes2 println(result2) } }Set(20, 30) Set(20, 30)
Set logic is helpful in some programs. A set is a map with no values: it can store a hashed lookup table of distinct keys. But no associated values may be added.