kms333
kms333

Reputation: 3257

Scala transform a list of maps into a map of lists

I have the following input:

List(
 Map("A" -> 1, "B" -> 2, "C" -> 3),
 Map("A" -> 4, "B" -> 5, "C" -> 6),
 Map("A" -> 7, "B" -> 8, "C" -> 9)
)

which I want to transform into:

Map(
 "A" -> List(1,4,7),
 "B" -> List(2,5,8),
 "C" -> List(3,6,9)
)

I have tried to use transpose but I'm not getting anywhere.

Upvotes: 0

Views: 687

Answers (1)

Mikel San Vicente
Mikel San Vicente

Reputation: 3863

You need to flatten, then groupBy and then mapValues to keep the list

list.flatten.groupBy(_._1).mapValues(_.map(_._2))

Upvotes: 2

Related Questions