Janek Bogucki
Janek Bogucki

Reputation: 5123

How to transpose a map with list values in Scala

How can this map of list,

Map (
   "a" -> List(1, 2)
)

be transposed to this list of maps primarily using methods from the Scala libraries?

List(
  Map("a" -> 1),
  Map("a" -> 2)
)

I can code a solution myself but I am more interested in using library functionality so the preferred solution should use the Scala library where possible while remaining compact and moderately legible.

This second example illustrates the required transformation with a map with more than one entry.

From this,

Map (
   10 -> List("10a", "10b", "10c"),
   29 -> List("29a", "29b", "29c")
)

to this,

List(
  Map(
    10 -> "10a",
    29 -> "29a"),
  Map(
    10 -> "10b",
    29 -> "29b"),
  Map(
    10 -> "10c",
    29 -> "29c")
)

It can be assumed that all values are lists of the same size.

Optionally the solution could handle the case where the values are empty lists but that is not required. If the solution supports empty list values then this input,

Map (
   "a" -> List()
)

should result in List().

Upvotes: 6

Views: 3413

Answers (1)

Régis Jean-Gilles
Régis Jean-Gilles

Reputation: 32719

val m = Map (
   10 -> List("10a", "10b", "10c"),
   29 -> List("29a", "29b", "29c")
)

m.map{ case (k, vs) =>
  vs.map(k -> _)
}.toList.transpose.map(_.toMap)

Note that this also handles your "empty list" case

Upvotes: 9

Related Questions