map的用法

53 阅读1分钟
def main(args: Array[String]): Unit = {
  // 创建可变的Map
  val scores = scala.collection.mutable.Map("alice"90, "bob"85)
  //添加
  scores += ("max"100)

  println(scores)

  //创建不可变的Map
  val provinceInfo = scala.collection.immutable.Map("42""湖北")
  // provinceInfo +
  val new
object Map02 {
  def main(args: Array[String]): Unit = {
    // 创建可变的Map 键 值 对
    val scores = scala.collection.mutable.Map("alice"90, "bob1"85)
    //1. 添加
    scores += ("max"100)

    // 2. 删除 alice 删除操作是根据Key来做的
    scores -= "alice"

    // 3. 查询。 查看bob的分数。 rst 是一个Option类型
    val rst = scores.get("bob1")
    if(rst.isEmpty){
    println("bob1没有成绩")
    } else {
      println(rst.get)
    }
    // 4. 打印scores
    println(scores)
    for ((key,value) <- scores){
      println(s"${key}, ${value}分")
    }

    // foreach
    scores.foreach({
      case (key,value) => println(s"${key}, ${value}分")
    })

image.png

image.png

image.png