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

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (8)

我有一个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"
提问于
用户回答回答于

地图反演有点复杂。

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为一组元组。groupByMap使用旧值作为新键创建一个新的。然后通过删除键(先前值)元素来取消元组值。

用户回答回答于

不依赖于奇特的隐含参数的替代flatten,如通过yishaiz要求

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))

扫码关注云+社区

领取腾讯云代金券