2016-07-06 3 views
1

값이 이미 있는지 확인하려면 특정 키의 값을 모두 확인해야합니다. 아래 코드를 사용하면 항상 마지막 값을 키에 추가합니다. 전체 값 목록을 반복하는 방법은 무엇입니까?스칼라 해시 맵에서 지정된 키의 값을 반복합니다.

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

지도에는 동일한 키에 둘 이상의 값을 포함 할 수 없습니다. 마지막 하나가 이전 값보다 우선합니다. 대신 멀티 맵을 사용할 수 있습니다 (http://www.scala-lang.org/api/2.9.0/scala/collection/mutable/MultiMap.html) –

답변

2

키는 HashMap에서 독특하다. 동일한 키에 대해 여러 값을 가질 수 없습니다. 값이 세트 안에 포함하거나, @TzachZohar가 지적으로 더 간단한 경우 당신이 할 수있는 것은 HashMap[Int, Set[String]]을 가지고 확인하는 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

왜 멀티 맵이 필요합니까? HashMap [Int, Set [String]]로 충분할 것으로 보인다. –

+1

'MultiMap'은'HashMap [Int, Set [String]]'주변의 편리한 래퍼입니다. 'mm.addBinding'을 호출하는 것만으로 집합에 데이터를 추가 할 수 있습니다. 대신에'Map'에서 집합을 추출하고 추가 된 데이터로 새로운 집합을 추가하는 번거 로움을 피할 수 있습니다. –

관련 문제