newToScala newToScala - 3 months ago 18
Scala Question

Reverse a map of type [Int, Seq[Int]]

I need to reverse a map

customerIdToAccountIds:Map[Int, Seq[Int]]


such that each account ID is a key to a list of all the customer IDs of the account (many-to-many relationship):

accountIdToCustomerIds:Map[Int, Seq[Int]]


What is a good idiomatic way to accomplish this? Thanks!

Input:

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)


Output:

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

Answer
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
Comments