反转[Int,Seq [Int]]类型的地图

时间:2016-08-03 20:53:31

标签: scala

我需要反转地图

customerIdToAccountIds:Map[Int, Seq[Int]]

这样每个帐户ID都是帐户所有客户ID列表的关键字(多对多关系):

accountIdToCustomerIds:Map[Int, Seq[Int]]

实现这一目标的良好惯用方法是什么?谢谢!

输入:

val customerIdToAccountIds:Map[Int, Seq[Int]] = Map(1 -> Seq(5,6,7), 2 -> Seq(5,6,7), 3 -> Seq(5,7,8))
val accountIdToCustomerIds:Map[Int, Seq[Int]] = ???

1 -> Seq(5,6,7)
2 -> Seq(5,6,7)
3 -> Seq(5,7,8)

输出:

5 -> Seq(1,2,3)
6 -> Seq(1,2)
7 -> Seq(1,2,3)
8 -> Seq(3)

2 个答案:

答案 0 :(得分:3)

val m = Map( 1 -> Seq(5,6,7)
           , 2 -> Seq(5,6,7)
           , 3 -> Seq(5,7,8) )

// Map inverter: from (k -> List(vs)) to (v -> List(ks))
m flatten {case(k, vs) => vs.map((_, k))} groupBy (_._1) mapValues {_.map(_._2)}

//result: Map(8 -> List(3), 5 -> List(1, 2, 3), 7 -> List(1, 2, 3), 6 -> List(1, 2))

答案 1 :(得分:1)

val customerIdToAccountIds = Map(1 -> Seq(5, 6, 7), 2 -> Seq(5, 6, 7), 3 -> Seq(5, 7, 8))

  val accountIdToCustomerIds = customerIdToAccountIds.toSeq.flatMap {
    case (customerId, accountIds) => accountIds.map { accountId => (customerId, accountId) } // swap
  }.groupBy(_._2).mapValues(_.map(_._1)) // groupBy accountId and extract customerId from tuples