Set

19 阅读1分钟

set的定义

package jue.lan
import scala.collection.mutable  // 导入可变集合

object set03 {
  def main(args: Array[String]): Unit = {
    // 1. 创建可变 Set(存储字符串类型)
    val fruitSet = mutable.Set("苹果", "香蕉", "橙子")

    // 2. 添加元素(自动去重)
    fruitSet += "葡萄"
    fruitSet += "香蕉"  // 重复元素,添加无效
    println("添加元素后:" + fruitSet)

    // 3. 删除元素
    fruitSet -= "橙子"
    println("删除元素后:" + fruitSet)

    // 4. 判断元素是否存在
    val hasApple = fruitSet.contains("苹果")
    println("集合中是否有苹果?" + hasApple)

    // 5. 遍历集合(无序输出)
    println("\n遍历集合元素:")
    for (fruit <- fruitSet) {
      print(fruit + " ")
    }
  }
}

不可变与可变 Set 的区别

package jue.lan

object set01 {
  def main(args: Array[String]): Unit = {
    // 默认情况下,使用的Set是不可变的。
    val set1 = scala.collection.immutable.Set(1, 2, 3, 1, 1, 1, 1)
    // 可变Set
    val set2 = scala.collection.mutable.Set(1, 2, 3)

    // 添加操作
    // 可变的set可以直接修改它自己
    set2 += 20
    // 不可变的set不能直接修改它自己
    // set1 += 2
    println(set2)
  }
}

set常见操作

package jue.lan

object set02 {
  def main(args: Array[String]): Unit = {
    // 可变Set
    val set1 = scala.collection.mutable.Set(1, 2, 3)

    // 1. 添加
    set1 += 1
    set1 += 4

    // 2. 移除
    set1 -= 2

    // 3. 判断一个元素是否存在
    val value = 5
    if (set1.contains(value)) {
      println(s"${value}存在")
    } else {
      println(s"${value}不存在")
    }
    // 4. 合并另一个set
    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)
  }
}