Scala Map:组合具有相同值的键?

Scala Map: Combine keys with the same value?

假设我有一个Map喜欢

val x = Map(1 -> List("a", "b"), 2 -> List("a"), 
            3 -> List("a", "b"), 4 -> List("a"), 
            5 -> List("c"))

我如何从中创建一个新的 Map,其中键是 x 中具有相同值的 List 个键,例如,我如何实现

def someFunction(m: Map[Int, List[String]]): Map[List[Int], List[String]] = 
  // stuff that would turn x into
  // Map(List(1, 3) -> List("a", "b"), List(2, 4) -> List("a"), List(5) -> List("c"))

?

您可以将 Map 转换为 List,然后使用 groupBy 聚合每个元组的第一个元素:

x.toList.groupBy(_._2).mapValues(_.map(_._1)).map{ case (x, y) => (y, x) }

// res37: scala.collection.immutable.Map[List[Int],List[String]] = 
//        Map(List(2, 4) -> List(a), List(1, 3) -> List(a, b), List(5) -> List(c))

或者如@Dylan 评论的那样,使用 _.swap 切换元组的元素:

x.toList.groupBy(_._2).mapValues(_.map(_._1)).map(_.swap)