1. scala> val scores = Map("Alice" -> 90, "Bob" -> 88)
2. scores: scala.collection.immutable.Map[String,Int] = Map(Alice -> 90, Bob -> 88)
• 构造一个可变映射
3. scala> val scores1 = scala.collection.mutable.Map("Alice" -> 90, "Bob" -> 88)
4. scores1: scala.collection.mutable.Map[String,Int] = Map(Bob -> 88, Alice -> 90)
• 构造一个空映射,需要选定一个映射实现并给出类型参数(注意最后是 方括号[] )
5. scala> val scores2 = new scala.collection.mutable.HashMap[String, Int]
6. scores2: scala.collection.mutable.HashMap[String,Int] = Map()
• 使用()获取映射中的值某个键对应的值
7. scala> val aliceScore = scores("Alice")
8. aliceScore: Int = 90
• 判断映射中是否包括某个指定键的值,用contains方法
9. scala> val bobScore = if(scores.contains("Bob")) scores("Bob") else 0
10. bobScore: Int = 88
11.
12. // 简洁写法
13. scala> val bobScore1 = scores.getOrElse("Bob", 0)
14. bobScore1: Int = 88
• 可变映射中更新某个映射中的值或添加一个新的映射关系
15. scala> val scores1 = scala.collection.mutable.Map("Alice" -> 90, "Bob" -> 88)
16. scores1: scala.collection.mutable.Map[String,Int] = Map(Bob -> 88, Alice -> 90)
17.
18. scala> scores1("Bob") = 99
19.
20. scala> scores1
21. res1: scala.collection.mutable.Map[String,Int] = Map(Bob -> 99, Alice -> 90)
22.
23.
24. // 如果key不存在,添加一个新的映射关系
25. scala> scores1("Fred") = 79
26.
27. scala> scores1
28. res3: scala.collection.mutable.Map[String,Int] = Map(Bob -> 99, Fred -> 79, Alice -> 90)
• 使用+=操作来添加多个关系(key不存在就添加,存在就更新)
29. scala> scores1 += ("Yezhiwei" -> 100, "Fred" -> 90)
30. res4: scores1.type = Map(Bob -> 99, Fred -> 90, Alice -> 90, Yezhiwei -> 100)
31.
32. scala> scores1
33. res5: scala.collection.mutable.Map[String,Int] = Map(Bob -> 99, Fred -> 90, Alice -> 90, Yezhiwei -> 100)
• 使用-=操作来移除某个键值对
34. scala> scores1 -= "Bob"
35. res6: scores1.type = Map(Fred -> 90, Alice -> 90, Yezhiwei -> 100)
36.
37. scala> scores1
38. res7: scala.collection.mutable.Map[String,Int] = Map(Fred -> 90, Alice -> 90, Yezhiwei -> 100)
• 不可变的映射可以有同样的操作,只是返回一个新的映射,而不会更新原对象
• 遍历映射中的所有键值对
39. scala> for((k, v) <- scores)
40. | println(k + ":" + v)
41.
42. // 运行结果
43. Alice:90
44. Bob:88
• 像Java一样,keySet和values方法访问键或值
45. scala> scores1.keys
46. res9: Iterable[String] = Set(Fred, Alice, Yezhiwei)
47.
48. scala> for(v <- scores.values) println (v)
49. 90
50. 88