Converting A Map[String, Seq[String]] To A Seq[(String, String)] in Scala My current code: 

val headers : Map[String, Seq[String]] = ...
//NOTE:  ("key" -&gt; Seq()) is  valid entry
headers.toList flatMap {x =&gt; x._2 map { y =&gt; (x._1 -&gt; y) }}


This feels clumsy...is there a better way to do this?

Goal

I have a Map[String, Seq[String]] representing all the headers in an HTTP request.   That needs to be translated to a Seq[(String, String)] in order to be passed to a method that expects that headers to be stored in that format.

The code is supposed to convert to this format.   The pair "something" -> Seq("val1", "val2", "val3") would be translated to 3 (String,String)'s.   "something" -> Seq() would be translated to 0.   

Concern

I'm still getting the hang of some aspects of the functional approach.  In a lot of cases, this one included, it feels like I'm building hard-to read, overly complex code.  I get that it's just a tolist + two maps, but this seems way less clear than some of the imperative alternatives, for example:

val ret = mutable.Seq[(String,String]()
for (kv &lt;- headers; value &lt;- kv._2) ret :+ (kv._1, value)


or even:

Set[Tuple2[String,String]] ret = new HashSet[Tuple2[String,String]]()
for (key : headers.keySet) {
  for (value : headers.get(key) {
     ret.add(new Tuple2(key, value))
  } 
}
I don't see how the functional code looks clumsy or difficult to read. If you have problems reading functional code, than don't write it - the imperative code is entirely fine, as long as the side effects remain local to a single function.

A lot of readability can be gained by giving your intermediate values useful names and to apply a different formatting:

headers.toSeq flatMap {
  case (parameter, values) =&gt;
     values map (parameter -&gt; _)
}


No need to squash everything into a single line or to use tuples ugly _X accessors.

Another way to write your code is:

for ((parameter, values) &lt;- m.toSeq; v &lt;- values)
  yield parameter -&gt; v


which looks very similar to the imperative solution but is exactly the same as the code before.

Write code that belongs to your skill level. If you don't feel fine with shorter and more functional code, then let it longer and more imperative. Improve your skills during the next months and refactor the code once you come back and see the need for it.