newToScala
newToScala

Reputation: 407

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)

Upvotes: 1

Views: 123

Answers (2)

insan-e
insan-e

Reputation: 3922

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

Upvotes: 1

jwvh
jwvh

Reputation: 51271

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

Upvotes: 3

Related Questions