set的定义
package jue.lan
import scala.collection.mutable
object set03 {
def main(args: Array[String]): Unit = {
val fruitSet = mutable.Set("苹果", "香蕉", "橙子")
fruitSet += "葡萄"
fruitSet += "香蕉"
println("添加元素后:" + fruitSet)
fruitSet -= "橙子"
println("删除元素后:" + fruitSet)
val hasApple = fruitSet.contains("苹果")
println("集合中是否有苹果?" + hasApple)
println("\n遍历集合元素:")
for (fruit <- fruitSet) {
print(fruit + " ")
}
}
}
不可变与可变 Set 的区别
package jue.lan
object set01 {
def main(args: Array[String]): Unit = {
val set1 = scala.collection.immutable.Set(1, 2, 3, 1, 1, 1, 1)
val set2 = scala.collection.mutable.Set(1, 2, 3)
set2 += 20
println(set2)
}
}
set常见操作
package jue.lan
object set02 {
def main(args: Array[String]): Unit = {
val set1 = scala.collection.mutable.Set(1, 2, 3)
set1 += 1
set1 += 4
set1 -= 2
val value = 5
if (set1.contains(value)) {
println(s"${value}存在")
} else {
println(s"${value}不存在")
}
val set2 = scala.collection.mutable.Set("语文")
val set3 = scala.collection.mutable.Set("数学", "英语")
set2 ++= set3
val set4 = scala.collection.mutable.Set("绿茶","饮料")
val set5 = scala.collection.mutable.Set("打游戏","打球","绿茶")
val set6 = set4.intersect(set5)
val set7 = scala.collection.mutable.Set("绿茶","饮料")
val set8 = scala.collection.mutable.Set("打游戏","打球","绿茶")
val set9 = set7.diff(set8)
println(set8)
}
}