d-_-b
d-_-b

Reputation: 4522

How to transform map into another?

What would be the most efficient(elegant) way to transform the following Map

Map("aaa" -> Seq(1, 2, 3), "bbb" -> Seq(1, 2), "ccc" -> Seq(1, 3))

into

Map(1 -> Seq("aaa", "bbb", "ccc"), 2 -> Seq("aaa", "bbb"), 3 -> Seq("aaa", "ccc"))

?

Upvotes: 1

Views: 188

Answers (1)

Tim
Tim

Reputation: 27421

For Scala 2.13:

Map("aaa" -> Seq(1, 2, 3), "bbb" -> Seq(1, 2), "ccc" -> Seq(1, 3))
  .toList
  .flatMap{ case (k,v) => v.map(_ -> k) }
  .groupMap(_._1)(_._2)

For earlier versions you will need to replace groupMap with group followed by map

Upvotes: 2

Related Questions