2016-07-06 54 views
1

我需要檢查給定鍵的所有值以查看該值是否已經存在。通過下面的代碼,我總能得到最後一個值。如何迭代整個值列表?遍歷scala散列映射中給定鍵的值

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

所以你想有某種*歷史*您地圖? –

+2

映射不能包含同一個鍵​​的多個值。最後一個覆蓋前一個。您可能想使用MultiMap(http://www.scala-lang.org/api/2.9.0/scala/collection/mutable/MultiMap.html) –

回答

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 
+0

爲什麼需要MultiMap?看來HashMap [Int,Set [String]]就足夠了。 –

+1

'MultiMap'是'HashMap [Int,Set [String]]'方便的包裝。你可以簡單地通過調用'mm.addBinding'來追加數據到集合中,而不需要從Map中提取集合,然後將新集合添加到新集合中。 –