Home »
Scala
Set &() Method in Scala
By IncludeHelp Last updated : November 14, 2024
The Set &() method in Scala
The &() method in the Set is used to create a new set in Scala. This new set created contains all elements from the other two sets that are common for both of the given sets i.e. new set created is the intersection of two sets.
Syntax
set1.&(set2)
Parameters
- set2 – It represents the set for the intersection.
Return Value
It returns a new set that has all elements of both the sets.
Let's see a few examples, for the usage of this function,
Example 1: When both sets have common elements
object myObject {
def main(args: Array[String]): Unit = {
val set1 = Set(13, 89, 57, 23, 96)
println("Set1 : " + set1)
val set2 = Set(1, 90, 13, 54, 89, 234, 54) // Fixed 01 to 1
println("Set2 : " + set2)
val set3 = set1.&(set2)
println("The intersection of two sets : " + set3)
}
}
Output
Set1 : HashSet(57, 89, 96, 13, 23)
Set2 : HashSet(234, 13, 54, 90, 89, 1)
The intersection of two sets : HashSet(89, 13)
Example 2: When sets donot have common elements
object myObject {
def main(args: Array[String]): Unit = {
val set1 = Set(13, 89, 57, 23, 96)
println("Set1 : " + set1)
val set2 = Set(1, 90, 54, 234, 54) // Fixed 01 to 1
println("Set2 : " + set2)
val set3 = set1.&(set2)
println("The intersection of two sets : " + set3)
}
}
Output
Set1 : HashSet(57, 89, 96, 13, 23)
Set2 : Set(1, 90, 54, 234)
The intersection of two sets : HashSet()