Scala的集合类Map,跟集(Set) 类似,Scala提供了Map的可变和不可变的版本,用类的继承关系来区分。在 scala.collection包里面有一个基础的 Map 特质,还有两个子特质,都叫Map,可变的那个位于 scala.collection.mutable,而不可变的那个位于 scala.collection.immutable。
创建一个 Map:
1、scala> var D: Map[Char, List[String]] = Map() D: Map[Char,List[String]] = Map() 2、scala> import scala.collection.mutable import scala.collection.mutable scala> val treasureMap = mutable.Map[Int, List[String]]() treasureMap: scala.collection.mutable.Map[Int,List[String]] = Map()
通过 -> 和 += 的方法向 Map 里面添加键值对(key/value pair):
scala> list res108: List[String] = List(Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday) scala> treasureMap += (1 -> list) res107: treasureMap.type = Map(1 -> List(Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday))
通过 -= 的方法将 Map 中对应的元素删除:
scala> D('a') res114: List[String] = List(a, b, c) scala> D -= ('a') scala> D res116: Map[Char,List[String]] = Map()
获得 Map 中 key 对应的value:
scala> treasureMap res109: scala.collection.mutable.Map[Int,List[String]] = Map(1 -> List(Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday)) scala> treasureMap(1) res110: List[String] = List(Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday)
如果你更倾向于使用不可变的映射,则不需要任何引入,因为默认的映射就是不可变的
scala> val romanNumeral = Map(1 -> "A", 2 -> "B", 3 -> "C", 4 -> "D", 5 -> "E") romanNumeral: scala.collection.immutable.Map[Int,String] = Map(5 -> E, 1 -> A, 2 -> B, 3 -> C, 4 -> D) scala> romanNumeral(2) res0: String = B scala> romanNumeral += (6 -> "F") <console>:26: error: value += is not a member of scala.collection.immutable.Map[Int,String] Expression does not convert to assignment because receiver is not assignable. romanNumeral += (6 -> "F") ^
Scala的 Map中 如果 key 相同的话,在做 += 操作的时候 key 所对应的 value 会被覆盖成新的元素
scala> D res3: Map[Char,List[String]] = Map() scala> D += ('a' -> a); scala> D res5: Map[Char,List[String]] = Map(a -> List(a, b, c)) scala> D += ('a' -> list); scala> D res7: Map[Char,List[String]] = Map(a -> List(Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday))