문제

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

도움이 되었습니까?

해결책

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top