pfari
pfari

Reputation: 101

Scala: flip key-value map

I need to convert the following map:

Map(1 -> Seq("A", "E"), 2 -> Seq("D", "G"))

to:

Map("a" -> 1, "d" -> 2, "e" -> 1, "g" -> 2)

How can I solve it?

Thanks!!!

Upvotes: 1

Views: 197

Answers (5)

Andrey Tyukin
Andrey Tyukin

Reputation: 44908

Assuming that m is your input map,

for ((v, ks) <- m; k <- ks) yield (k.toLowerCase, v)

produces:

Map(a -> 1, e -> 1, d -> 2, g -> 2)

This is essentially a 1:1 translation of the recipe: "For each pair of integer value v and list of letters ks from the original map, take each letter k from ks and add the pair (k, v) to the new map".

Upvotes: 4

Puneeth Reddy V
Puneeth Reddy V

Reputation: 1568

We can also use collect to achieve this

scala> val map =Map(1 -> Seq("A", "E"), 2 -> Seq("D", "G"))
map: scala.collection.immutable.Map[Int,Seq[String]] = Map(1 -> List(A, E), 2 -> List(D, G))

 scala> map.collect{case (k,v) => v.map(_.toLowerCase -> k)}.flatten.toMap
//res2: scala.collection.immutable.Map[String,Int] = Map(a -> 1, e -> 1, d -> 2, g -> 2)

Upvotes: 0

Mzf
Mzf

Reputation: 5260

The other answer are correct but for someone that is new to scala they can be hard to understand. The below is simple and easy to understand

val z = Map(1 -> Seq("A", "E"), 2 -> Seq("D", "G"))
z.map{case (i,l) => l.map(s=> (s.toLowerCase->i))}.flatten.toMap

Upvotes: 0

Nagarjuna Pamu
Nagarjuna Pamu

Reputation: 14825

Use flatMap and convert inner list using map to desired form.

Warning: Seqs must not have duplicates.

scala> val map = Map(1 -> Seq("A", "E"), 2 -> Seq("D", "G"))
map: scala.collection.immutable.Map[Int,Seq[String]] = Map(1 -> List(A, E), 2 -> List(D, G))

scala> map.flatMap { case (k, v) => v.map(_.toLowerCase -> k) }
res0: scala.collection.immutable.Map[String,Int] = Map(a -> 1, e -> 1, d -> 2, g -> 2)

Upvotes: 4

Ramesh Maharjan
Ramesh Maharjan

Reputation: 41957

you can do something like below

val m = Map(1 -> Seq("A", "E"), 2 -> Seq("D", "G"))

println(m.flatMap(x => x._2.map(y => (y.toLowerCase, x._1))))

and you would get

Map(a -> 1, e -> 1, d -> 2, g -> 2)

Upvotes: 2

Related Questions