迭代scala哈希映射中给定键的值

时间:2016-07-06 13:37:19

标签: scala hashmap

我需要检查给定键的所有值,以查看该值是否已存在。使用下面的代码,我总是得到最后一个值添加到密钥。如何迭代整个值列表?

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 = ()

1 个答案:

答案 0 :(得分:2)

密钥在HashMap中是唯一的。您不能为同一个密钥设置多个值。您可以做的是HashMap[Int, Set[String]]并检查该值是否包含在集合中,或者甚至更简单,如@TzachZohar所指出的,MultiMap

scala> import collection.mutable.{ HashMap, MultiMap, Set }
import collection.mutable.{HashMap, MultiMap, Set}

scala> val mm = new HashMap[Int, Set[String]] with MultiMap[Int, String]
mm: scala.collection.mutable.HashMap[Int,scala.collection.mutable.Set[String]] with scala.collection.mutable.MultiMap[Int,String] = Map()

scala> mm.addBinding(0, "a")
res9: <refinement>.type = Map(0 -> Set(a))

scala> mm.addBinding(0, "b")
res10: <refinement>.type = Map(0 -> Set(a, b))

scala> mm.entryExists(0, _ == "b")
res11: Boolean = true