Use of Scala Map collection

Immutable Map

Create Map

val map1: Map[String, Int] = Map("a" -> 1, "b" -> 2, "c" -> 3)
val map1: Map[String, Int] = Map(("a", 1), ("b", 2), ("c", 3))

Collection traversal

map1.foreach((kv: (String, Int)) => println(kv))
map1.foreach(println)

Get all keys

val keys: Iterable[String] = map1.keys
for (key <- keys) {
    
    
  println(key + "," + map1.get(key))
}

Get the value corresponding to the specified key

  • In Scala, in order to avoid the null pointer exception, the return value of the get method is of Opetion type.
val a: Option[Int] = map1.get("a")
println(a)   // Some(1)
val d: Option[Int] = map1.get("d")
println(d)  // None
val dd: Int = map1.get("d").getOrElse(10)
println(dd)   // 10

Variable Map

Create Map

val map2: mutable.Map[String, Int] = mutable.Map[String,Int]("abc" -> 10, "bcd" -> 20, "cde" -> 30)

Add element

 map2.put("fff",50)

Delete element

map2.remove("fff")

Modify elements

map2.update("abc",111)
println(map2)
map2("abc") = 123
println(map2)

Guess you like

Origin blog.csdn.net/FlatTiger/article/details/114583157