简体   繁体   中英

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?

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM