Search code examples
scalacollectionsfunctional-programmingflatmap

Flatten a map into pairs (key, value) in Scala


Say I construct the following map in scala:

val map = Map.empty[String, Seq[String]] + ("A" -> ("1", "2", "3", "4"), "B" -> ("2", "3"), "C" -> ("3", "4"))

My output should be a Sequence of single key, value pairs. Namely, it should look like this:

[("A", "1"), ("A", "2"), ("A", "3"), ("A", "4"), ("B", "2"), ("B", "3"), ("B", "2"), ("C", "3"),
("C", "4")]

How can I obtain this using flatMap?


Solution

  • I would guess that your original goal was to create next map (note added Seqs in map):

    val map = Map.empty[String, Seq[String]] + ("A" -> Seq("1", "2", "3", "4"), "B" -> Seq("2", "3"), "C" -> Seq("3", "4"))
    

    Then you will be able to easily transform it easily with:

    val result = map.toSeq.flatMap { case (k, v) => v.map((k, _)) }