1.给集添加元素
1)用+=、++=和add给可变集添加元素。
scala> var set = scala.collection.mutable.Set[Int]()
set: scala.collection.mutable.Set[Int] = Set() scala> set += 1
res48: scala.collection.mutable.Set[Int] = Set(1) scala> set += (2,3)
res49: scala.collection.mutable.Set[Int] = Set(1, 2, 3) scala> set ++= Vector(4,5)
res50: scala.collection.mutable.Set[Int] = Set(1, 5, 2, 3, 4) scala> set.add(6)
res51: Boolean = true scala> set
res52: scala.collection.mutable.Set[Int] = Set(1, 5, 2, 6, 3, 4) scala> set.add(5)
res53: Boolean = false
2)使用+和++方法,通过向前一个集添加元素生成一个新的集。
scala> val set = Set(1,3,5,2,7)
set: scala.collection.immutable.Set[Int] = Set(5, 1, 2, 7, 3) scala> val set1 = set + (8,9)
set1: scala.collection.immutable.Set[Int] = Set(5, 1, 9, 2, 7, 3, 8) scala> val set2 = set1 ++ List(10,11)
set2: scala.collection.immutable.Set[Int] = Set(5, 10, 1, 9, 2, 7, 3, 11, 8)
2.从集中删除元素
1)处理可变集时,用-=和--=从集中删除元素。
scala> var set = scala.collection.mutable.Set(1,2,3,4,5)
set: scala.collection.mutable.Set[Int] = Set(1, 5, 2, 3, 4) scala> set -= 1
res57: scala.collection.mutable.Set[Int] = Set(5, 2, 3, 4) scala> set -= (2,3)
res58: scala.collection.mutable.Set[Int] = Set(5, 4) scala> set --= Array(4,5)
res59: scala.collection.mutable.Set[Int] = Set()
2)处理可变集,retain和clear删除集中元素。
scala> var set = scala.collection.mutable.Set(1,2,3,4,5)
set: scala.collection.mutable.Set[Int] = Set(1, 5, 2, 3, 4) scala> set.retain(_ > 2);println(set)
Set(5, 3, 4) scala> set.clear;println(set)
Set()
3)处理可变集时,remove的返回值可以提示集是否有元素被删除。
scala> var set = scala.collection.mutable.Set(1,2,3,4,5)
set: scala.collection.mutable.Set[Int] = Set(1, 5, 2, 3, 4) scala> set.remove(2);println(set)
Set(1, 5, 3, 4) scala> set.remove(3)
res64: Boolean = true scala> set
res65: scala.collection.mutable.Set[Int] = Set(1, 5, 4)
4)处理不可变集时,可以使用-和--操作符删除元素,同时将结果重新赋给一个新的变量。
scala> val s1 = Set(1,2,3,4,5)
s1: scala.collection.immutable.Set[Int] = Set(5, 1, 2, 3, 4) scala> val s2 = s1 -1
s2: scala.collection.immutable.Set[Int] = Set(5, 2, 3, 4) scala> val s3 = s2 - (2,3)
s3: scala.collection.immutable.Set[Int] = Set(5, 4) scala> val s4 = s3 -- Array(4,5)
s4: scala.collection.immutable.Set[Int] = Set()
3.使用可排序集
1)SortedSet返回元素时有序的。
scala> val s = scala.collection.SortedSet(3,1,2,5,6,9)
s: scala.collection.SortedSet[Int] = TreeSet(1, 2, 3, 5, 6, 9) scala> val s = scala.collection.SortedSet("c","g","a","b")
s: scala.collection.SortedSet[String] = TreeSet(a, b, c, g)
2)LinkedHashSet按照插入顺序保存元素的。
scala> val s = scala.collection.mutable.LinkedHashSet(10,8,3,5,7)
s: scala.collection.mutable.LinkedHashSet[Int] = Set(10, 8, 3, 5, 7)