Set 是不重复元素的集合。分为可变 Set 和不可变 Set
1. 可变的set
object SetApp extends App {
//可变的set
val mutableSet = new collection.mutable.HashSet[Int]
mutableSet.add(1)
mutableSet.add(2)
mutableSet.add(3)
mutableSet.add(3)
mutableSet.add(4)
// println(mutableSet) //HashSet(1, 2, 3, 4)
// mutableSet.remove(2)
// println(mutableSet) //HashSet(1, 3, 4)
// println(mutableSet.mkString(",")) //1,2,3,4
// println(mutableSet.min) //获取 Set 中最小元素
// println(mutableSet.max) //获取 Set 中最大元素
}
2. 不可变的set
不可变 Set 没有 add 方法,可以使用 + 添加元素,但是此时会返回一个新的不可变 Set,原来的 Set 不变
object SetApp extends App {
//不可变的set
val immutableSet = new collection.immutable.HashSet[String]
val ints = immutableSet+"abc" //ints HashSet(abc)
val newints = ints + "cdb"
println(newints) // HashSet(abc, cdb)
}
3. Set间的操作
多个 Set 之间可以进行求交集或者合集等操作。
object ScalaApp extends App {
// 声明有序 Set
val mutableSet = collection.mutable.SortedSet(1, 2, 3, 4, 5)
val immutableSet = collection.immutable.SortedSet(3, 4, 5, 6, 7)
// 两个 Set 的合集 输出:TreeSet(1, 2, 3, 4, 5, 6, 7)
println(mutableSet ++ immutableSet)
// 两个 Set 的交集 输出:TreeSet(3, 4, 5)
println(mutableSet intersect immutableSet)
}