Set. In Scala programs we often need to track unique elements—ones not already encountered. A set allows only distinct elements—it eliminates duplicates.
Operators. With special operators, like "++," we combine sets. In the two sets, any duplicate elements will be lost. Scala provides the Set type with simple syntax.
First example. 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.
Detail The set is immutable. To modify a set in Scala we can only create a new set, such as with a special operator.
Detail This method returns true or false. It tells us whether the argument exists within the set.
// Create a Set of two strings.
val animals = Set("bird", "fish")
// See if this string is in the set.
// This string is not contained in the set.
Combine set. 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.
Here We use the "++" operator to combine two sets. Both sets have 15 as an element, and the resulting set has one instance of this value.
// 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(results3)Set(10, 11, 15)
Set(2, 3, 15)
Set(10, 2, 3, 11, 15)
Intersect. 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.
Detail Set theory is an important part of mathematics. But for programs, it usually just makes some operations easier.
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)
// Short syntax for intersection.
val result2 = codes1 & codes2
Sets are assets. 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.