Scala集合(Set)

Scala Set是相同類型成對的不同元素的集合。換句話說,一個集合是不包含重複元素的集合。 集合有兩種:不可變(immutable)和可變(mutable)。可變對象和不可變對象之間的區別在於,當對象不可變時,對象本身無法更改。

默認情況下,Scala使用不可變的集合(Set)。 如果要使用可變集合(Set),則必須明確導入scala.collection.mutable.Set類。 如果要在同一集合中使用可變集合和不可變集合,則可以繼續引用不可變集作為集合(Set),但可以將可變集合稱為mutable.Set

// Empty set of integer type
var s : Set[Int] = Set()

// Set of integer type
var s : Set[Int] = Set(1,3,5,7)
// 或者

var s = Set(1,3,5,7)

通過定義一個空集合,類型注釋是必要的,因為系統需要將具體的類型分配給變數。

集合基本操作

所有對集合的操作都可以用以下三種方法來表示:

序號 方法 描述
1 head 此方法返回列表的第一個元素。
2 tail 此方法返回由除第一個之外的所有元素組成的列表。
3 isEmpty 如果列表為空,則此方法返回true,否則返回false

以下示例顯示如何使用上述方法。

示例

object Demo {
   def main(args: Array[String]) {
      val fruit = Set("apples", "oranges", "pears")
      val nums: Set[Int] = Set()

      println( "Head of fruit : " + fruit.head )
      println( "Tail of fruit : " + fruit.tail )
      println( "Check if fruit is empty : " + fruit.isEmpty )
      println( "Check if nums is empty : " + nums.isEmpty )
   }
}

將上述程式保存在原始檔案:Demo.scala中,使用以下命令編譯和執行此程式。

D:\>scalac Demo.scala
D:\>scala Demo

Head of fruit : apples
Tail of fruit : Set(oranges, pears)
Check if fruit is empty : false
Check if nums is empty : true

連接集合

您可以使用++運算符或Set.++()方法連接兩個或多個集合,但是在添加集合時,它將刪除重複的元素。

以下是連接兩個集合的例子 -

object Demo {
   def main(args: Array[String]) {
      val fruit1 = Set("apples", "oranges", "pears")
      val fruit2 = Set("mangoes", "banana")

      // use two or more sets with ++ as operator
      var fruit = fruit1 ++ fruit2
      println( "fruit1 ++ fruit2 : " + fruit )

      // use two sets with ++ as method
      fruit = fruit1.++(fruit2)
      println( "fruit1.++(fruit2) : " + fruit )
   }
}

將上述程式保存在原始檔案:Demo.scala中,使用以下命令編譯和執行此程式。

D:\>scalac Demo.scala
D:\>scala Demo

fruit1 ++ fruit2 : Set(banana, apples, mangoes, pears, oranges)
fruit1.++(fruit2) : Set(banana, apples, mangoes, pears, oranges)

在集合中查找最大值,最小元素

可以使用Set.min方法和Set.max方法來分別找出集合中元素的最大值和最小值。 以下是顯示程式的示例。

object Demo {
   def main(args: Array[String]) {
      val num = Set(5,6,9,20,30,45)

      // find min and max of the elements
      println( "Min element in Set(5,6,9,20,30,45) : " + num.min )
      println( "Max element in Set(5,6,9,20,30,45) : " + num.max )
   }
}

將上述程式保存在原始檔案:Demo.scala中,使用以下命令編譯和執行此程式。

D:\>scalac Demo.scala
D:\>scala Demo

Min element in Set(5,6,9,20,30,45) : 5
Max element in Set(5,6,9,20,30,45) : 45

查找交集值

可以使用Set.&Set.intersect方法來查找兩個集合之間的交集(相交值)。嘗試以下示例來顯示用法。

object Demo {
   def main(args: Array[String]) {
      val num1 = Set(5,6,9,20,30,45)
      val num2 = Set(50,60,9,20,35,55)

      // find common elements between two sets
      println( "num1.&(num2) : " + num1.&(num2) )
      println( "num1.intersect(num2) : " + num1.intersect(num2) )
   }
}

將上述程式保存在原始檔案:Demo.scala中,使用以下命令編譯和執行此程式。

D:\>scalac Demo.scala
D:\>scala Demo

num1.&(num2) : Set(20, 9)
num1.intersect(num2) : Set(20, 9)

Scala集方法

有關可用方法的完整列表,請查看Scala的官方文檔。


上一篇: Scala集合 下一篇: Scala模式匹配