Scala中的Set&()方法 (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.
集合中的&()方法用于在Scala中创建一个新集合。 创建的这个新集合包含两个给定集合中共有的其他两个集合中的所有元素,即,创建的新集合是两个集合的交集。
Syntax:
句法:
set1.&(set2)
parameter(s):
参数:
set2 – It represents the set for the intersection.
set2 –表示相交的集合。
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,
让我们看几个例子,关于这个函数的用法,
Case 1: When both sets have common elements.
情况1:两组都具有相同的元素。
object myObject
{
def main(args:Array[String])
{
val set1 = Set(13, 89, 57, 23, 96)
println("Set1 : "+ set1)
val set2 = Set(01, 90, 13, 54, 89, 234, 54)
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)
Case 2: When sets donot have common elements
情况2:集合没有共同元素时
object myObject
{
def main(args:Array[String])
{
val set1 = Set(13, 89, 57, 23, 96)
println("Set1 : "+ set1)
val set2 = Set(01, 90, 54, 234, 54)
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()