2

I have a map as given below in scala.

Map("x"-> "abc", "y"->"adc","z"->"abc", "l"-> "ert","h"->"dfg", "p"-> "adc")

I want the output as follows:

Map("abc"->["x","z"],"adc"->["y" , "p"], "ert"->"l", "dfg"->"h")

So, the output has the array as the value of those those keys which had same values in inital map. How can I get that done optimally?

Ravi Ranjan
  • 353
  • 1
  • 6
  • 22
  • 2
    Possible duplicate of [Elegant way to invert a map in Scala](http://stackoverflow.com/questions/2338282/elegant-way-to-invert-a-map-in-scala) – Yuval Itzchakov Jan 20 '17 at 06:56
  • 1
    `"l"` and `"h"` in the result should probably read `["l"]` and `["h"]`, right? Then Brian's answer from below is exactly what you want. – user152468 Jan 20 '17 at 07:25

1 Answers1

3

A groupBy followed by some manipulation of the values it outputs should do.

scala> m.groupBy(x => x._2).mapValues(_.keys.toList)
res10: scala.collection.immutable.Map[String,List[String]]
  = Map(abc -> List(x, z), dfg -> List(h), ert -> List(l), adc -> List(y, p))
Brian
  • 20,195
  • 6
  • 34
  • 55