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

The CMS developers love. Open Source, API-first and Enterprise-grade. Try BloomReach CMS for free.

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


BloomReach CMS: the API-first CMS of the future. Open-source & enterprise-grade. - As a Java developer, you will feel at home using Maven builds and your favorite IDE (e.g. Eclipse or IntelliJ) and continuous integration server (e.g. Jenkins). Manage your Java objects using Spring Framework, write your templates in JSP or Freemarker. Try for free.

Topics:
java ,scala ,transpose ,list ,map

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}