-9

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

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
dataProcs
  • 55
  • 1
  • 13

2 Answers2

1

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?

jwvh
  • 50,871
  • 7
  • 38
  • 64
0

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))

Duelist
  • 1,562
  • 1
  • 9
  • 24
  • And what if I want to convert that List to a map? If I try with .toMap method it just get the (k,v) with last v seen and I want to keep them – dataProcs Oct 18 '18 at 09:36
  • You can't do that because of `Map`, this data structure can have only unique keys. Please, read [this](https://docs.scala-lang.org/overviews/collections/maps.html) and [this](https://en.wikipedia.org/wiki/Associative_array) articles – Duelist Oct 18 '18 at 09:42
  • If you want to keep your values, leave them in a tuple. You can also store them in a list or in another `SeqLike` data structure, so your map might look like `Map[String, Seq[String]]`. – Duelist Oct 18 '18 at 09:44