在Scala中反转Map(String - > List)

时间:2017-11-15 20:53:22

标签: scala scala-collections

我有一个Map [String,List [String]],我想反转它。例如,如果我有类似

的东西
  "1" -> List("a","b","c")
  "2" -> List("a","j","k")
  "3" -> List("a","c")

结果应为

  "a" -> List("1","2","3")
  "b" -> List("1")
  "c" -> List("1","3")
  "j" -> List("2")
  "k" -> List("2")

我试过这个:

  m.map(_.swap)

但是它返回一个Map [List [String],String]:

  List("a","b","c") -> "1"
  List("a","j","k") -> "2" 
  List("a","c") -> "3"

3 个答案:

答案 0 :(得分:7)

地图反演有点复杂。

val m = Map("1" -> List("a","b","c")
           ,"2" -> List("a","j","k")
           ,"3" -> List("a","c"))

m flatten {case(k, vs) => vs.map((_, k))} groupBy (_._1) mapValues {_.map(_._2)}
//res0: Map[String,Iterable[String]] = Map(j -> List(2), a -> List(1, 2, 3), b -> List(1), c -> List(1, 3), k -> List(2))

Map展平为一组元组。 groupBy将使用旧值作为新密钥创建新的Map。然后通过删除键(先前值)元素来取消元组值。

答案 1 :(得分:2)

不依赖requested by yishaizflatten的奇怪隐式参数的替代方法:

val m = Map(
  "1" -> List("a","b","c"),
  "2" -> List("a","j","k"),
  "3" -> List("a","c"),
)

val res = (for ((digit, chars) <- m.toList; c <- chars) yield (c, digit))
  .groupBy(_._1)          // group by characters
  .mapValues(_.unzip._2)  // drop redundant digits from lists

res foreach println

给予:

(j,List(2))
(a,List(1, 2, 3))
(b,List(1))
(c,List(1, 3))
(k,List(2))

答案 2 :(得分:0)

可以使用简单的嵌套式理解来反转地图,以使“值列表”中的每个值都是反转地图中的键,而各个键分别为其值

implicit class MapInverter[T] (map: Map[T, List[T]]) {
def invert: Map[T, T] = {
  val result = collection.mutable.Map.empty[T, T]

  for ((key, values) <- map) {
    for (v <- values) {
      result += (v -> key)
    }
  }
  result.toMap
}

用法:

Map(10 -> List(3, 2), 20 -> List(16, 17, 18, 19)).invert