Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

How to Transpose a Collection in Scala [Snippets]

DZone's Guide to

How to Transpose a Collection in Scala [Snippets]

These quick snippets will teach you how to transpose a Map of Lists into a List of Maps and how to transpose a List of Lists.

· Java Zone ·
Free Resource

FlexNet Code Aware, a free scan tool for developers. Scan Java, NuGet, and NPM packages for open source security and open source license compliance issues.

Goal

You want to transpose a Map of Lists to a List of maps.

Solution

def main(args: Array[String]) {
    val m = Map(
        "breakfast" -> List("cereals", "omelet", "fruits"),
        "lunch" -> List("sandwich", "salad", "steak"),
        "dinner" -> List("pasta", "taco", "soup"))
    val dietList = m.map {
        case (k, vs) =>
            vs.map(k -> _)
        }.toList.transpose.map(_.toMap)
    print(dietList)


Output

List(
    Map(breakfast -> cereals, lunch -> sandwich, dinner -> pasta),
    Map(breakfast -> omelet, lunch -> salad, dinner -> taco),
    Map(breakfast -> fruits, lunch -> steak, dinner -> soup)
)


Goal

You want to transpose a List of Lists.

Solution

def main(args: Array[String]) {
    val list = List(List("a1", "a2", "a3", "a4"), List("b1", "b2", "b3", "b4"), List("c1", "c2", "c3", "c4"))
    val transposedList = list.transpose
    println(transposedList)
}


Output

List(
    List(a1, b1, c1),
    List(a2, b2, c2),
    List(a3, b3, c3),
    List(a4, b4, c4)
)


 Scan Java, NuGet, and NPM packages for open source security and license compliance issues. 

Topics:
java ,scala ,transpose ,list ,map

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}