List("a","b","c") "2" -> List("a","j",-6ren">
gpt4 book ai didi

scala - 在Scala中反转 map (字符串->列表)

转载 作者:行者123 更新时间:2023-12-04 05:19:41 24 4
gpt4 key购买 nike

我有一个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"

最佳答案

map 反转有点复杂。

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。然后,通过删除键(以前的值)元素来取消元组的值。

关于scala - 在Scala中反转 map (字符串->列表),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47317040/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com