cool breeze
cool breeze

Reputation: 4811

Reversing a Map but using the values as keys, and keys as values

I have a map defined below. The key represents a UserID and the value represents and AddressId.

val m: Map[Int, List[Int]]

I want to know reverse the map, meaning for every item in each List I want to make it a key, and the value be a list of keys.

So basically for every AddressID I will have a list of UserID's.

How can I do this?

I know I can use mapValues but I need to somehow refer back to the key.

Doing this won't create the list:

m.map(k => (k._2, k._1))

Thoughts?

Upvotes: 0

Views: 174

Answers (2)

Oleg Pyzhcov
Oleg Pyzhcov

Reputation: 7353

Regular Scala

m
    .toVector
    .flatMap   { case (k, vs) => vs.map(_ -> k) }
    .groupBy   { case (v, _) => v }
    .mapValues { _.map { case (_, k) => k } }

If you're using cats or Scalaz:

m.toVector foldMap { case (k, vs) => vs foldMap (v => Map(v -> List(k)))  }

Upvotes: 2

Guillaume
Guillaume

Reputation: 1286

Here is a potential solution:

val m = Map( 1 -> List("a","b"), 2 -> List("c","a" ))

val m1 = m.toList.flatMap{ case(key,valueList) => valueList.map(value => (value,key) )}.groupBy{ _._1  } 

m1.map{ case(key,valueList) => key -> valueList.map{case (x,y) => y  } }

Not the most elegant method but it seems to work on my side.

Upvotes: 0

Related Questions