# Scala Set(集合)
Scala Set(集合)是沒有重復的對象集合,所有的元素都是唯一的。
Scala 集合分為可變的和不可變的集合。
默認情況下,Scala 使用的是不可變集合,如果你想使用可變集合,需要引用 **scala.collection.mutable.Set** 包。
默認引用 scala.collection.immutable.Set,不可變集合實例如下:
```
val set = Set(1,2,3)
println(set.getClass.getName) //
println(set.exists(_ % 2 == 0)) //true
println(set.drop(1)) //Set(2,3)
```
如果需要使用可變集合需要引入 scala.collection.mutable.Set:
```
import scala.collection.mutable.Set // 可以在任何地方引入 可變集合
val mutableSet = Set(1,2,3)
println(mutableSet.getClass.getName) // scala.collection.mutable.HashSet
mutableSet.add(4)
mutableSet.remove(1)
mutableSet += 5
mutableSet -= 2
println(mutableSet) // Set(5, 3, 4)
val another = mutableSet.toSet
println(another.getClass.getName) // scala.collection.immutable.Set
```
> **注意:** 雖然可變Set和不可變Set都有添加或刪除元素的操作,但是有一個非常大的差別。對不可變Set進行操作,會產生一個新的set,原來的set并沒有改變,這與List一樣。 而對可變Set進行操作,改變的是該Set本身,與ListBuffer類似。
## 集合基本操作
Scala集合有三個基本操作:
* `head` 返回集合第一個元素
* `tail` 返回一個集合,包含除了第一元素之外的其他元素
* `isEmpty` 在集合為空時返回true
對于Scala集合的任何操作都可以使用這三個基本操作來表達。實例如下:
```
object Test {
def main(args: Array[String]) {
val site = Set("Runoob", "Google", "Baidu")
val nums: Set[Int] = Set()
println( "第一網站是 : " + site.head )
println( "最后一個網站是 : " + site.tail )
println( "查看列表 site 是否為空 : " + site.isEmpty )
println( "查看 nums 是否為空 : " + nums.isEmpty )
}
}
```
執行以上代碼,輸出結果為:
```
$ vim Test.scala
$ scala Test.scala
第一網站是 : Runoob
最后一個網站是 : Set(Google, Baidu)
查看列表 site 是否為空 : false
查看 nums 是否為空 : true
```
## 連接集合
你可以使用 **++** 運算符或 **Set.++()** 方法來連接兩個集合。如果元素有重復的就會移除重復的元素。實例如下:
```
object Test {
def main(args: Array[String]) {
val site1 = Set("Runoob", "Google", "Baidu")
val site2 = Set("Faceboook", "Taobao")
// ++ 作為運算符使用
var site = site1 ++ site2
println( "site1 ++ site2 : " + site )
// ++ 作為方法使用
site = site1.++(site2)
println( "site1.++(site2) : " + site )
}
}
```
執行以上代碼,輸出結果為:
```
$ vim Test.scala
$ scala Test.scala
site1 ++ site2 : Set(Faceboook, Taobao, Google, Baidu, Runoob)
site1.++(site2) : Set(Faceboook, Taobao, Google, Baidu, Runoob)
```
## 查找集合中最大與最小元素
你可以使用 **Set.min** 方法來查找集合中的最小元素,使用 **Set.max** 方法查找集合中的最大元素。實例如下:
```
object Test {
def main(args: Array[String]) {
val num = Set(5,6,9,20,30,45)
// 查找集合中最大與最小元素
println( "Set(5,6,9,20,30,45) 集合中的最小元素是 : " + num.min )
println( "Set(5,6,9,20,30,45) 集合中的最大元素是 : " + num.max )
}
}
```
執行以上代碼,輸出結果為:
```
$ vim Test.scala
$ scala Test.scala
Set(5,6,9,20,30,45) 集合中的最小元素是 : 5
Set(5,6,9,20,30,45) 集合中的最大元素是 : 45
```
## 交集
你可以使用 **Set.&** 方法或 **Set.intersect** 方法來查看兩個集合的交集元素。實例如下:
```
object Test {
def main(args: Array[String]) {
val num1 = Set(5,6,9,20,30,45)
val num2 = Set(50,60,9,20,35,55)
// 交集
println( "num1.&(num2) : " + num1.&(num2) )
println( "num1.intersect(num2) : " + num1.intersect(num2) )
}
}
```
執行以上代碼,輸出結果為:
```
$ vim Test.scala
$ scala Test.scala
num1.&(num2) : Set(20, 9)
num1.intersect(num2) : Set(20, 9)
```
## Scala Set 常用方法
下表列出了 Scala Set 常用的方法:
| 方法 | 描述 |
| --- | --- |
| **def +(elem: A): Set\[A\]** | 為集合添加新元素,x并創建一個新的集合,除非元素已存在 |
| **def -(elem: A): Set\[A\]** | 移除集合中的元素,并創建一個新的集合 |
| **def contains(elem: A): Boolean** | 如果元素在集合中存在,返回 true,否則返回 false。 |
| **def &(that: Set\[A\]): Set\[A\]** | 返回兩個集合的交集 |
| **def &~(that: Set\[A\]): Set\[A\]** | 返回兩個集合的差集 |
| **def +(elem1: A, elem2: A, elems: A*): Set\[A\]** | 通過添加傳入指定集合的元素創建一個新的不可變集合 |
| **def ++(elems: A): Set\[A\]** | 合并兩個集合 |
| **def -(elem1: A, elem2: A, elems: A*): Set\[A\]** | 通過移除傳入指定集合的元素創建一個新的不可變集合 |
| **def addString(b: StringBuilder): StringBuilder** | 將不可變集合的所有元素添加到字符串緩沖區 |
| **def addString(b: StringBuilder, sep: String): StringBuilder** | 將不可變集合的所有元素添加到字符串緩沖區,并使用指定的分隔符 |
| **def apply(elem: A)** | 檢測集合中是否包含指定元素 |
| **def count(p: (A) => Boolean): Int** | 計算滿足指定條件的集合元素個數 |
| **def copyToArray(xs: Array\[A\], start: Int, len: Int): Unit** | 復制不可變集合元素到數組 |
| **def diff(that: Set\[A\]): Set\[A\]** | 比較兩個集合的差集 |
| **def drop(n: Int): Set\[A\]]** | 返回丟棄前n個元素新集合 |
| **def dropRight(n: Int): Set\[A\]** | 返回丟棄最后n個元素新集合 |
| **def dropWhile(p: (A) => Boolean): Set\[A\]** | 從左向右丟棄元素,直到條件p不成立 |
| **def equals(that: Any): Boolean** | equals 方法可用于任意序列。用于比較系列是否相等。 |
| **def exists(p: (A) => Boolean): Boolean** | 判斷不可變集合中指定條件的元素是否存在。 |
| **def filter(p: (A) => Boolean): Set\[A\]** | 輸出符合指定條件的所有不可變集合元素。 |
| **def find(p: (A) => Boolean): Option\[A\]** | 查找不可變集合中滿足指定條件的第一個元素 |
| **def forall(p: (A) => Boolean): Boolean** | 查找不可變集合中滿足指定條件的所有元素 |
| **def foreach(f: (A) => Unit): Unit** | 將函數應用到不可變集合的所有元素 |
| **def head: A** | 獲取不可變集合的第一個元素 |
| **def init: Set\[A\]** | 返回所有元素,除了最后一個 |
| **def intersect(that: Set\[A\]): Set\[A\]** | 計算兩個集合的交集 |
| **def isEmpty: Boolean** | 判斷集合是否為空 |
| **def iterator: Iterator\[A\]** | 創建一個新的迭代器來迭代元素 |
| **def last: A** | 返回最后一個元素 |
| **def map\[B\](f: (A) => B): immutable.Set\[B\]** | 通過給定的方法將所有元素重新計算 |
| **def max: A** | 查找最大元素 |
| **def min: A** | 查找最小元素 |
| **def mkString: String** | 集合所有元素作為字符串顯示 |
| **def mkString(sep: String): String** | 使用分隔符將集合所有元素作為字符串顯示 |
| **def product: A** | 返回不可變集合中數字元素的積。 |
| **def size: Int** | 返回不可變集合元素的數量 |
| **def splitAt(n: Int): (Set\[A\], Set\[A\])** | 把不可變集合拆分為兩個容器,第一個由前 n 個元素組成,第二個由剩下的元素組成 |
| **def subsetOf(that: Set\[A\]): Boolean** | 如果集合中含有子集返回 true,否則返回false |
| **def sum: A** | 返回不可變集合中所有數字元素之和 |
| **def tail: Set\[A\]** | 返回一個不可變集合中除了第一元素之外的其他元素 |
| **def take(n: Int): Set\[A\]** | 返回前 n 個元素 |
| **def takeRight(n: Int):Set\[A\]** | 返回后 n 個元素 |
| **def toArray: Array\[A\]** | 將集合轉換為數字 |
| **def toBuffer[B >: A]: Buffer\[B\]** | 返回緩沖區,包含了不可變集合的所有元素 |
| **def toList: List\[A\]** | 返回 List,包含了不可變集合的所有元素 |
| **def toMap[T, U]: Map[T, U]** | 返回 Map,包含了不可變集合的所有元素 |
| **def toSeq: Seq\[A\]** | 返回 Seq,包含了不可變集合的所有元素 |
| **def toString(): String** | 返回一個字符串,以對象來表示 |
更多方法可以參考 [API文檔](http://www.scala-lang.org/api/current/scala/collection/immutable/List.html)
- Scala 教程
- Scala 簡介
- Scala 安裝
- Scala 基礎語法
- Scala 數據類型
- Scala 變量
- Scala 訪問修飾符
- Scala 運算符
- Scala IF...ELSE 語句
- Scala 循環
- Scala while 循環
- Scala do...while 循環
- Scala do...while 循環
- Scala break 語句
- Scala 函數
- Scala 函數傳名調用(call-by-name)
- Scala 指定函數參數名
- Scala 函數 - 可變參數
- Scala 遞歸函數
- Scala 高階函數
- Scala 函數嵌套
- Scala 匿名函數
- Scala 偏應用函數
- Scala 函數柯里化(Currying)
- Scala 閉包
- Scala 字符串
- Scala 數組
- Scala Collection
- Scala List(列表)
- Scala Set(集合)
- Scala Map(映射)
- Scala 元組
- Scala Option(選項)
- Scala Iterator(迭代器)
- Scala 類和對象
- Scala Trait(特征)
- Scala 模式匹配
- Scala 正則表達式
- Scala 異常處理
- Scala 提取器(Extractor)
- Scala 文件 I/O