object MapLearn {
def main(args: Array[String]): Unit = {
//创建Map
val map1 = Map("zhangsan" -> 10, "lisi" -> 5)
println(map1)
println(map1.getClass.getName)
val map2 = Map(("zhangsan", 10), ("lisi", 5))
println(map2)
println(map2.getClass.getName)
val map3 = scala.collection.mutable.Map("zhangsan" -> 10, "lisi" -> 5)
println(map3)
println(map3.getClass.getName)
println(map3("zhangsan"))
//访问map
val zhang = if (map3.contains("zhang")) {
map3("zhang")
} else -1
println(zhang)
// println(map3("zhang"))
println(map3.getOrElse("zhang", -1))
println(map3.getOrElse("zhangsan", -1))
println(map3.isEmpty)
println(map3.keys)
println(map3.values)
//map的修改
map3("zhangsan") = 90
map3("wangwu") = 100
println(map3.getOrElse("zhangsan", -1))
println(map3.getOrElse("wangwu", -1))
println(map3)
map3 += ("zhaoliu" -> 99)
map3 += (("gaoqi", 99))
println(map3)
map3 -= ("gaoqi")
println(map3)
//循环遍历
for (elem <- map3) {
println(elem._1 + ":" + elem._2)
}
for ((k, v) <- map3) {
println(k + ":" + v)
}
}
}
scala自学之路-15-map
最新推荐文章于 2023-07-14 09:58:01 发布