Scala Set Examples: contains, intersectCreate a Set to store unique elements in a collection. Use contains and intersect.
Set. On the beach, a great variety of seashells are visible. Suppose we want only unique ones. 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 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.
Immutable: The set is immutable. To modify a set in Scala we can only create a new set, such as with a special operator.
Contains: This method returns true or false. It tells us whether the argument exists within the set.
Scala program that uses set, contains
// 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.
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.
Scala program that combines two sets
// 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.
Set(10, 11, 15)
Set(2, 3, 15)
Set(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.
Logic: Set theory is an important part of mathematics. But for programs, it usually just makes some operations easier.
Scala program that finds intersection
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 in programming languages usually include methods like intersect(). And intersection is a core part of set theory. For a review, Wikipedia is a good choice.
Quote: Set theory is the branch of mathematical logic that studies sets, which informally are collections of objects.Set theory: Wikipedia
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.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to email@example.com.