Search code examples
scalaseq

Condense scala map


Imagine I have

case class Thing(intValue: Int, stringValue: String)

With this I can make a map Map[Int, Thing]

val myMap = Map(1->Thing(100,"abc"), 2->Thing(100,"abcd"), 3->Thing(100,"abcde"), 4->Thing(200,"xyz"))

The original keys in the map aren't important. I want to somehow convert this data structure into

Map(100-> Seq("abc", "abcd", "abcde"), 200-> Seq("xyz"))


Solution

  • You can do it by groupBy

    myMap.groupBy(_._2.intValue).mapValues(_.values.map(_.stringValue))