How would be the method to perform the following operation?
Convert a Map K1->(v1,v2), K2->(v1,v2)
to K1->v1,K1->v2,K2->v1,K2->V2
How would be the method to perform the following operation?
Convert a Map K1->(v1,v2), K2->(v1,v2)
to K1->v1,K1->v2,K2->v1,K2->V2
To go from Map[String,(String, String)]
to List[Map[String,String]]
:
val mss = Map("s"->("a","b"), "t"->("a","c"))
mss.toList.flatMap{case (k,(a,b)) => List((k,a),(k,b))}.map(Map(_))
The last step of turning every result tuple into a Map
is pretty pointless. What's the use of a Map
with only one key->value pair?
You should firstly convert your Map
to List
or to Seq
(if you want more general type) and then you can use flatMap
. The example with toList
:
val map = Map("a" -> ("1", "2"), "b" -> ("3", "4"))
map.toList.flatMap {
case (k, (v1, v2)) => List(k -> v1, k -> v2)
}
// res0: List[(String, String)] = List((a,1), (a,2), (b,3), (b,4))
Firstly your values mapped into lists of tuples, so the intermediate result will be:
List(List((a,1), (a,2)), List((b,3), (b,4)))
and then it flattens and you get list of tuples:
List((a,1), (a,2), (b,3), (b,4))