Reputation: 353
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?
Upvotes: 2
Views: 2738
Reputation: 20285
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))
Upvotes: 3