My current code:
val headers : Map[String, Seq[String]] = ...
//NOTE: ("key" -> Seq()) is valid entry
headers.toList flatMap {x => x._2 map { y => (x._1 -> 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 <- headers; value <- 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))
}
}