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()
翻譯自: https://www.includehelp.com/scala/set-and-method.aspx