user908853
user908853

Reputation:

Convert Map with list values to list of tuples

I have a Map[String,List[String]] and I would like to have this converted to a List[(String, String)] where the first element of a given Tuple is a map key and the second element is a member of the corresponding list from the map.

For example:

Map[String,List[String]](
  "a" -> List("aa", "ab", "ac"),
  "b" -> List("ba", "bb")
)

Should become:

List((a,aa), (a,ab), (a,ac), (b,ba), (b,bb))

What I do currently is this, you can find a demo here:

(for{
  tuple <- mapOfLists
}yield{
  tuple._2.map{ elem =>
    (tuple._1,elem)
  }
}).toList.flatten

It works just fine but I think could be done better, is there a completely functional way to do this?

Upvotes: 1

Views: 2264

Answers (3)

elm
elm

Reputation: 20405

Using a for comprehension with a simpler yield, like this

for ( (k,l) <- mapOfLists.toList ; v <- l ) yield (k,v)

Upvotes: 1

Vladimir Matveev
Vladimir Matveev

Reputation: 127711

import scala.collection.breakOut

val result: List[(String, String)] = 
   mapOfLists.flatMap({ case (k, l) => l.map(k -> _) })(breakOut)

This way no intermediate list is created - flatMap will create the resulting list directly. But you need to put flatMap call into a context where a correct type can be inferred, like variable assignment with explicit type.

Upvotes: 0

Lee
Lee

Reputation: 144126

 mapOfLists.toList.flatMap({case (k, l) => l.map((k, _))})

Upvotes: 3

Related Questions