Ravi Ranjan
Ravi Ranjan

Reputation: 353

Aggregate/Reduce by key function for a map in scala

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

Answers (1)

Brian
Brian

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

Related Questions