Mapping is divided into mutable.Map and immutable mapping.
Map
Define Map, match the connection key-value pair ->
// 定义
val map = Map("a" -> 1, "b" -> 2, "c" -> 3)
println(map) // Map(a -> 1, b -> 2, c -> 3)
Read the element, through get, when there is a value, get Some, if there is no value, get None.
Because it is Some, you need to add another get to get the specific value, and you can also get the specific value through (key).
If you are not sure whether the value exists, you can use the getOrElse method, followed by a default value, if there is no corresponding value, it will return to this default value.
// 读取
println(map.get("a")) // Some(1)
println(map.get("a").get) // 1
println(map("a")) // 1
println(map.get("d")) // None
println(map.getOrElse("d", 0)) // 0
Loop traversal:
You can print each key-value pair directly, or get the key-value pair through _1 and _2 in the loop.
You can get the key collection through keys, or you can get the value collection through values
map.foreach(println) // (a,1) (b,2) (c,3)
map.foreach(e => println(e))// (a,1) (b,2) (c,3)
map.foreach(e => {
println(e._1 + "->" + e._2) // a->1 b->2 c->3
})
map.keys.foreach(println) // a b c
map.values.foreach(println) // 1 2 3
mutable.Map
Defined by mutable.Map
val map = mutable.Map("a" -> 1, "b" -> 2, "c" -> 3)
println(map) // Map(b -> 2, a -> 1, c -> 3)
Reading and loop traversal are the same as the above, without repeating the description.
Assignment:
map.+=("d" -> 4) // 等同map += ("d" -> 4)
println(map) // Map(b -> 2, d -> 4, a -> 1, c -> 3)
map("e") = 5
println(map) // Map(e -> 5, b -> 2, d -> 4, a -> 1, c -> 3)
map.put("f", 6)
println(map) // Map(e -> 5, b -> 2, d -> 4, a -> 1, c -> 3, f -> 6)
map.update("g", 7) // 不存在则新增
println(map) // Map(e -> 5, b -> 2, d -> 4, a -> 1, c -> 3, f -> 6)
delete:
map -= "g"
println(map) // Map(e -> 5, b -> 2, d -> 4, a -> 1, c -> 3, f -> 6)
map.remove("f")
println(map) // Map(e -> 5, b -> 2, d -> 4, a -> 1, c -> 3)
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。