Scala Map集合

package com.wyh.day01

object ScalaMap {
  def main(args: Array[String]): Unit = {
    /**
      * 不可变Map
      *
      */
    //创建不可变集合,两种写法
    var map1 = Map((1604093026, "王友虎"), 1604093029 -> "赵以浩")

    //通过key获取到Option
    var res1 = map1.get(1604093026)
    //通过get获取到具体的值
    println(res1.get)

    //获取key对应的value值,如果没有,返回指定的默认值
    println(map1.getOrElse(16044, "默认值"))
    println(map1.getOrElse(1604093029, "默认值"))

    //获取不存在的key返回None
    println(map1.get(123456))
    println("=" * 100)

    //遍历Map
    for (elem <- map1) {
      var key = elem._1
      var value = elem._2
      println(key + "\t" + value)
    }

    println("=" * 100)

    //添加元素,可以同时添加多个元素,返回一个新的Map
    val map2 = map1 + ((1604093002, "小李"), 16044 -> "xiaoxiao")
    for (elem <- map2) {
      var key = elem._1
      var value = elem._2
      println(key + "\t" + value)
    }

    /**
      *
      * 可变Map
      */

    import scala.collection.mutable

    var map4 = mutable.Map(("品牌", "小米"), "型号" -> "小米6")

    val value = map4("品牌")
    println(value)

    println("=" * 100)

    var map5 = mutable.Map[String, Int]()

    //往其中添加元素
    map5.put("学生1", 12138)
    map5.put("学生2", 15478)
    map5.put("学生3", 11438)
    map5.put("学生4", 17138)

    val i = map5.getOrElse("xue", 1)
    println(i)

    for (elem <- map5) {
      var key = elem._1
      var value = elem._2
      println(key + "\t" + value)
    }


    val values = map5.values
    for (elem <- values) {
      println(elem)
    }

  }
}
posted @ 2020-01-20 13:37  Xiaohu_BigData  阅读(425)  评论(0编辑  收藏  举报