1.构造映射
object Test { def main(args: Array[String]): Unit = { //不可变映射 val scores1 = Map("alice" -> 90, "tom" -> 100) // 值不能被改变 val scores2 = Map(("alice", 90), ("tom", 100)) //可变映射 val scores3 = scala.collection.mutable.Map("alice" -> 90, "tom" -> 100) //空的映射 val map = scala.collection.mutable.HashMap[String, Int] } }
2.获取映射中的值
object Test { def main(args: Array[String]): Unit = { val scores1 = Map("alice" -> 90, "tom" -> 100) // 获取值 println(scores1("alice")) //没有的话报错 println(scores1.getOrElse("lili", 80)) println(scores1.get("alice")) //Some(90) 没有 None Option对象 } }
3.更新映射中的值
object Test { def main(args: Array[String]): Unit = { val scores1 = scala.collection.mutable.Map("alice" -> 90, "tom" -> 100) scores1("alice") = 100 println(scores1("alice")) //100 scores1("zhangsan") = 80 //没有该键,则添加 println(scores1("zhangsan")) //添加多个 scores1 += ("lili" -> 70, "sam" -> 60) //移除 scores1 -= "sam" } }
4.迭代映射
object Test { def main(args: Array[String]): Unit = { val scores1 = scala.collection.mutable.Map("alice" -> 90, "tom" -> 100) //迭代 //获取所有键 for (i <- scores1.keySet) { print(i + "--") } println() for (i <- scores1.keys) { print(i + "--") } println() //获取所有值 for (i <- scores1.values) { print(i + "--") } println() //获取键值对 for ((k, v) <- scores1) { println((k, v) + "--") } } }
5.元祖
object Test { def main(args: Array[String]): Unit = { val tuple = (1,2,"a","b") println(tuple._1) } }
7.拉链操作
object Test { def main(args: Array[String]): Unit = { val tuple = (1, 2, "a", "b") println(tuple._1) val a = Array(1, 2, 3) val b = Array("a", "b", "c") val c = a.zip(b) for ((k, v) <- c) { println((k, v)) } // (1,a) // (2,b) // (3,c) c.toMap } }