简介
Scala Set(集合)是没有重复的对象的容器,所有的元素都是唯一的。
Scala 集合分为可变的和不可变的集合。
默认情况下,Scala 使用的是不可变集合,如果你想使用可变集合,需要引用 scala.collection.mutable.Set 包。默认引用 scala.collection.immutable.Set,不可变集合实例如下:
默认的不可变Set
val set = Set(1,2,3,1)
set: Set[Int] = Set(1, 2, 3)
println(set.getClass.getName)
scala.collection.immutable.Set$Set3
可变Set
import scala.collection.mutable.Set
val mutableSet = Set(1,2,3,4)
import scala.collection.mutable.Set
mutableSet: Set[Int] = Set(1, 2, 3, 4)
mutableSet.add(5)
mutableSet
res17_0: Boolean = true
res17_1: Set[Int] = Set(1, 5, 2, 3, 4)
mutableSet.remove(1)
mutableSet
res18_0: Boolean = true
res18_1: Set[Int] = Set(5, 2, 3, 4)
mutableSet += 6
res21: Set[Int] = Set(5, 2, 6, 3, 7, 4)
val another = mutableSet.toSet
println(another.getClass.getName)
scala.collection.immutable.HashSet$HashTrieSet
another: collection.immutable.Set[Int] = Set(5, 6, 2, 7, 3, 4)
注意: 虽然可变Set和不可变Set都有添加或删除元素的操作,但是有一个非常大的差别。对不可变Set进行操作,会产生一个新的set,原来的set并没有改变,这与List一样。 而对可变Set进行操作,改变的是该Set本身,与ListBuffer类似。
集合基本操作
Scala集合有三个基本操作:
- head 返回集合第一个元素
- tail 返回一个集合,包含除了第一元素之外的其他元素
- isEmpty 在集合为空时返回true
val set1 = Set(1,2,3,4,5)
set1: Set[Int] = Set(1, 5, 2, 3, 4)
set1.head
res24: Int = 1
set1.tail
res25: Set[Int] = Set(5, 2, 3, 4)
set1.isEmpty
res26: Boolean = false
res26: Boolean = false
val set2 = Set()
set2.isEmpty
set2: Set[Nothing] = Set()
res28_1: Boolean = true
查找集合中最大与最小元素
你可以使用 Set.min 方法来查找集合中的最小元素,使用 Set.max 方法查找集合中的最大元素。实例如下:
val num = Set(1,2,3,4,5,6,7)
num: Set[Int] = Set(1, 5, 2, 6, 3, 7, 4)
println("num 最小的元素: " + num.min)
println("num 最大的元素: " + num.max)
num 最小的元素: 1
num 最大的元素: 7
交集运算
交集
你可以使用 Set1.&Set2方法或 Set1.intersect(Set2) 方法来查看两个集合的交集元素。
并集
可以使用Set1++Set2 或者Set1.++(Set2)来求两个集合的并集
差集
使用Set1.&~Set2或者Set1.diff(Set2)
val set1 = Set(1,2,3,4)
val set2 = Set(3,4,5,6)
println("set1.&(set2): " + set1.&(set2))
println("set1.intersect(set2): " + set1.intersect(set2))
println("set1 ++ set2): " + (set1 ++ set2))
println("set1.++(set2): " + set1.++(set2))
println("set1.&~(set2): " + set1.&~(set2))
println("set1.diff(set2): " + set1.diff(set2))
set1.&(set2): Set(3, 4)
set1.intersect(set2): Set(3, 4)
set1 ++ set2): Set(5, 1, 6, 2, 3, 4)
set1.++(set2): Set(5, 1, 6, 2, 3, 4)
set1.&~(set2): Set(1, 2)
set1.diff(set2): Set(1, 2)