A set in Scala is a collection of unique items. We discard any repeating items when creating a set. The key point about Scala is that it includes both immutable and mutable sets. By definition, the set values contained in immutable sets cannot change. Immutable sets are the default set type used in Scala.
In order to define mutable sets, we should declare the
Scala.collection.mutable
library.
We can also create an empty set in Scala.
// difference is the use of `val` and `var` to define immutable and mutable sets.
// Immutable empty set
val empty_set = Set()
// Mutable empty set
var empty_set = Set()
Immutable or mutable sets can be defined in two ways:
Method 1
// In this method, the `type` refers to the datatype of the set Int, String etc.
// Immutable set
val set1: Set[type] = Set(n1, n2, n3)
// Mutable Set
var set1: Set[type] = Set(n1, n2, n3)
Method 2
// Immutable set
val set2 = Set(n1, n2, n3)
// Mutable Set
var set2 = Set(n1, n2, n3)
Let’s look at set examples using String and Integer data:
object Main extends App { val Asia: Set[String] = Set("India", "Pakistan", "Bangladesh", "Sri Lanka") val Europe = Set("England", "France", "Spain", "Germany", "Belgium", "Switzerland") // Displaying Set Asia println("Asia:") Asia.foreach(println) // Displaying Set Europe println("\nEurope:") Europe.foreach(println) // We can combine two sets using .++ method or ++ operator val countries = Asia.++(Europe) val countries2 = Asia ++ Europe // Displaying Set Europe println("\nCountries using method .+:") countries.foreach(println) println("\nCountries using operator ++:") countries2.foreach(println) }
Next, let’s perform set operations with Integer Data:
object Main extends App { // Let's do it with integers val numbers1: Set[Int] = Set(12,1,23,43,14,89) val numbers2: Set[Int] = Set(1,12,89,32,21,45) // performing union val union = numbers1.++(numbers2) println("Union: "+ union) // performing intersection val intersection = numbers1.&(numbers2) println("intersection: "+ intersection) }
RELATED TAGS
CONTRIBUTOR
View all Courses