6

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

2
  • 2
    It is more transpose, than flatten Commented Jul 25, 2013 at 8:30
  • Updated to use transpose. Commented Jul 25, 2013 at 8:33

1 Answer 1

9
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

Sign up to request clarification or add additional context in comments.

1 Comment

This fits my requirements perfectly and passes all my unit tests.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.