在scala哈希映射中遍历给定键的值

在scala哈希映射中遍历给定键的值,scala,hashmap,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("

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

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)}

键在
HashMap
中是唯一的。同一个键不能有多个值。您可以做的是使用一个
HashMap[Int,Set[String]]
并检查该值是否包含在集合中,或者更简单地说,正如@TzachZohar所指出的,一个:

scala>import collection.mutable.{HashMap,MultiMap,Set}
导入集合.mutable.{HashMap,MultiMap,Set}
scala>val mm=使用MultiMap[Int,String]新建HashMap[Int,Set[String]]
mm:scala.collection.mutable.HashMap[Int,scala.collection.mutable.Set[String]]和scala.collection.mutable.MultiMap[Int,String]=Map()
scala>mm.addBinding(0,“a”)
res9:.type=Map(0->Set(a))
scala>mm.addBinding(0,“b”)
res10:.type=Map(0->Set(a,b))
scala>mm.entryExists(0,==“b”)
res11:Boolean=true

那么您想拥有地图的某种历史记录吗?一个地图不能为同一个键包含多个值。最后一个覆盖上一个。您可能想改用MultiMap()为什么需要MultiMap?看来HashMap[Int,Set[String]]就足够了。
MultiMap
HashMap[Int,Set[String]]
的一个方便的包装器。只需调用
mm.addBinding
,就可以将数据附加到集合中,而无需麻烦地从
Map
中提取集合,然后将添加的数据附加到新集合中。
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 = ()
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