【发布时间】:2016-07-06 22:01:19
【问题描述】:
我需要检查给定键的所有值以查看该值是否已经存在。使用下面的代码,我总是将最后一个值添加到键中。如何遍历整个值列表?
val map = scala.collection.mutable.HashMap.empty[Int, String]
map.put(0, "a")
map.put(0, "b")
map.put(0, "c")
map.put(0, "d")
map.put(0, "e")
map.put(0, "f")
for ((k, v) <- map) {println("key: " + k + " value: " + v)}
输出:
map: scala.collection.mutable.HashMap[Int,String] = Map()
res0: Option[String] = None
res1: Option[String] = Some(a)
res2: Option[String] = Some(b)
res3: Option[String] = Some(c)
res4: Option[String] = Some(d)
res5: Option[String] = Some(e)
key: 0 value: f
res6: Unit = ()
【问题讨论】:
-
所以您想要了解地图的某种历史?
-
一个映射不能包含多个相同键的值。最后一个覆盖前一个。您可能想改用 MultiMap (scala-lang.org/api/2.9.0/scala/collection/mutable/MultiMap.html)