关于scala:Scala-集合

5次阅读

共计 783 个字符,预计需要花费 2 分钟才能阅读完成。

汇合分为可变汇合 mutable.Set 和不可变汇合 Set。

Set

// 定义
val set1 = Set(1, 2, 3, 1, 2, 3)
println(set1) // Set(1, 2, 3)
// 新增
val set2 = set1.+(4)
println(set2) // Set(1, 2, 3, 4)
val set3 = set1 + 4
println(set3) // Set(1, 2, 3, 4)
// 删除
val set4 = set3 - 1
println(set4) // Set(2, 3, 4)
// 加汇合
val set5 = Set(2, 3, 4, 5)
val set6 = set1 ++ set5
println(set6) // Set(5, 1, 2, 3, 4)
// 循环
set6.foreach(println)
// 并集
val set7 = Set(1, 2, 3) union (Set(2, 3, 4))
println(set7) // Set(1, 2, 3, 4)
// 差集
val set8 = Set(1, 2, 3) diff (Set(2, 3, 4))
println(set8) // Set(1)
// 交加
val set9 = Set(1, 2, 3) intersect (Set(2, 3, 4))
println(set9) // Set(2, 3)

mutable.Set

循环、并集、差集、交接同上,这里不做累述

// 定义
val set1 = mutable.Set(1, 2, 3)
// 加元素
set1 += 4
println(set1) // Set(1, 2, 3, 4)
set1.add(5)
println(set1) // Set(1, 5, 2, 3, 4)
// 删除
set1 -= 5
println(set1) // Set(1, 2, 3, 4)
set1.remove(1)
println(set1) // Set(2, 3, 4)
// 加汇合
set1 ++= mutable.Set(1, 2, 6)
println(set1) // Set(1, 5, 2, 6, 3, 4)
正文完
 0