Set 是一個無法放置相同元素的容器,元素都是唯一的,不會重複.有分為 mutable 及 immutable.
內容不可以變動
scala> val nums = Set(1,2,3,4,5,2,3)
nums: scala.collection.immutable.Set[Int] = Set(5, 1, 2, 3, 4)
判斷該元素是否存在 :
scala> nums(2)
res207: Boolean = true
scala> nums(6)
res208: Boolean = false
scala> nums contains 3
res213: Boolean = true
新增元素 :
scala> nums + 6
res210: scala.collection.immutable.Set[Int] = Set(5, 1, 6, 2, 3, 4)
scala> nums + (6,7,8)
res214: scala.collection.immutable.Set[Int] = Set(5, 1, 6, 2, 7, 3, 8, 4)
移除元素 :
scala> nums - 3
res212: scala.collection.immutable.Set[Int] = Set(5, 1, 2, 4)
scala> nums - (2,3)
res215: scala.collection.immutable.Set[Int] = Set(5, 1, 4)
使用位元符號做運算 :
scala> val newnums = Set(11,22,33,44,5)
newnums: scala.collection.immutable.Set[Int] = Set(5, 33, 22, 44, 11)
scala> nums & newnums
res218: scala.collection.immutable.Set[Int] = Set(5)
scala> nums | newnums
res219: scala.collection.immutable.Set[Int] = Set(5, 1, 33, 2, 22, 44, 3, 11, 4)
scala> nums union newnums
res220: scala.collection.immutable.Set[Int] = Set(5, 1, 33, 2, 22, 44, 3, 11, 4)
scala> nums &~ newnums
res221: scala.collection.immutable.Set[Int] = Set(1, 2, 3, 4)
內容可以變動
scala> import scala.collection.mutable.Set
import scala.collection.mutable.Set
scala> val mnums = Set(1,2,3,4,5)
mnums: scala.collection.mutable.Set[Int] = Set(1, 5, 2, 3, 4)
scala> mnums(2)
res0: Boolean = true
scala> mnums(6)
res1: Boolean = false
新增元素 :
scala> mnums += 6
res2: mnums.type = Set(1, 5, 2, 6, 3, 4)
scala> mnums
res3: scala.collection.mutable.Set[Int] = Set(1, 5, 2, 6, 3, 4)
scala> mnums += (7,8)
res4: mnums.type = Set(1, 5, 2, 6, 3, 7, 4, 8)
scala> mnums
res5: scala.collection.mutable.Set[Int] = Set(1, 5, 2, 6, 3, 7, 4, 8)
移除元素 :
scala> mnums -= 3
res6: mnums.type = Set(1, 5, 2, 6, 7, 4, 8)
scala> mnums -= (2,4)
res7: mnums.type = Set(1, 5, 6, 7, 8)
scala> mnums
res8: scala.collection.mutable.Set[Int] = Set(1, 5, 6, 7, 8)
複製元素 :
scala> val mnewnums = mnums.clone
mnewnums: scala.collection.mutable.Set[Int] = Set(1, 5, 6, 7, 8)
Sort 排序 :
scala> val nums = Set(3,1,5,4,8)
nums: scala.collection.mutable.Set[Int] = Set(1, 5, 3, 4, 8)
scala> collection.immutable.SortedSet[Int]() ++ nums
res10: scala.collection.immutable.SortedSet[Int] = TreeSet(1, 3, 4, 5, 8)
scala> collection.immutable.TreeSet[Int]() ++ nums
res11: scala.collection.immutable.TreeSet[Int] = TreeSet(1, 3, 4, 5, 8)