【问题标题】:iterate through values of given key in scala hash map遍历scala哈希图中给定键的值
【发布时间】: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 = ()

【问题讨论】:

标签: scala hashmap


【解决方案1】:

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

【讨论】:

  • 为什么需要MultiMap?看来 HashMap[Int, Set[String]] 就足够了。
  • MultiMapHashMap[Int, Set[String]] 的便捷包装器。您可以通过调用mm.addBinding 将数据附加到集合中,而不是费力地从Map 中提取集合,然后将添加的数据附加到新集合中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-01
  • 1970-01-01
  • 2016-08-19
  • 2018-06-28
  • 2011-05-08
相关资源
最近更新 更多