C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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")
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"))
Output
Set(bird, fish)
true
false
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.
println(results1)
println(results2)
println(results3)
Output
Set(10, 11, 15)
Set(2, 3, 15)
Set(10, 2, 3, 11, 15)
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)
println(result1)
// Short syntax for intersection.
val result2 = codes1 & codes2
println(result2)
Output
Set(20, 30)
Set(20, 30)
Quote: Set theory is the branch of mathematical logic that studies sets, which informally are collections of objects.
Set theory: Wikipedia