2010-09-09 33 views

回答

23

如果你可以失去重复键:

scala> val map = Map(1->"one", 2->"two", -2->"two") 
map: scala.collection.immutable.Map[Int,java.lang.String] = Map((1,one), (2,two), (-2,two)) 

scala> map.map(_ swap) 
res0: scala.collection.immutable.Map[java.lang.String,Int] = Map((one,1), (two,-2)) 

如果你不想访问的多重映射,只是一个地图集,则:

scala> map.groupBy(_._2).mapValues(_.keys.toSet) 
res1: scala.collection.immutable.Map[ 
    java.lang.String,scala.collection.immutable.Set[Int] 
] = Map((one,Set(1)), (two,Set(2, -2))) 

如果你坚持要一个MultiMap,则:

scala> import scala.collection.mutable.{HashMap, Set, MultiMap} 
scala> ((new HashMap[String,Set[Int]] with MultiMap[String,Int]) ++= 
    |   map.groupBy(_._2).mapValues(Set[Int]() ++= _.keys)) 
res2: scala.collection.mutable.HashMap[String,scala.collection.mutable.Set[Int]] 
with scala.collection.mutable.MultiMap[String,Int] = Map((one,Set(1)), (two,Set(-2, 2))) 
+0

+1为简洁,并为我介绍mapValues :-) – 2010-09-09 18:25:54

+0

一个更好的开始会更清晰,但例如, Map(1 - >“one”,2 - >“two”,3 - >“two”,4 - >“two”) – 2010-09-09 18:26:15

+0

@Rodney - 好的,好的,我会显示重叠的情况! – 2010-09-09 18:32:44

4
scala> val m1 = Map(1 -> "one", 2 -> "two", 3 -> "three", 4 -> "four") 
m1: scala.collection.immutable.Map[Int,java.lang.String] = Map((1,one), (2,two), (3,three), (4,four)) 

scala> m1.map(pair => pair._2 -> pair._1) 
res0: scala.collection.immutable.Map[java.lang.String,Int] = Map((one,1), (two,2), (three,3), (four,4)) 

编辑澄清的问题:

object RevMap { 
    def 
    main(args: Array[String]): Unit = { 
    val m1 = Map("one" -> 3, "two" -> 3, "three" -> 5, "four" -> 4, "five" -> 5, "six" -> 3) 

    val rm1 = (Map[Int, Set[String]]() /: m1) { (map: Map[Int, Set[String]], pair: (String, Int)) => 
               map + ((pair._2, map.getOrElse(pair._2, Set[String]()) + pair._1)) } 

    printf("m1=%s%nrm1=%s%n", m1, rm1) 
    } 
} 

% scala RevMap 
m1=Map(four -> 4, three -> 5, two -> 3, six -> 3, five -> 4, one -> 3) 
rm1=Map(4 -> Set(four, five), 5 -> Set(three), 3 -> Set(two, six, one)) 

我不确定这是否符合简洁规定。

+1

+1为工作解决方案。 :-) – missingfaktor 2010-09-09 18:46:27

0

如何:

implicit class RichMap[A, B](map: Map[A, Seq[B]]) 
    { 
    import scala.collection.mutable._ 

    def reverse: MultiMap[B, A] = 
    { 
     val result = new HashMap[B, Set[A]] with MultiMap[B, A] 

     map.foreach(kv => kv._2.foreach(result.addBinding(_, kv._1))) 

     result 
    } 
    } 

implicit class RichMap[A, B](map: Map[A, Seq[B]]) 
    { 
    import scala.collection.mutable._ 

    def reverse: MultiMap[B, A] = 
    { 
     val result = new HashMap[B, Set[A]] with MultiMap[B, A] 

     map.foreach{case(k,v) => v.foreach(result.addBinding(_, k))} 

     result 
    } 
    } 
相关问题