0
votes

Given the following:

val t: List[Map[String, Map[String, Int]]] = List(
  Map("a" -> Map("m" -> 1, "l" -> 21)),
    Map("a" -> Map("m" -> 2, "l" -> 22)),
    Map("a" -> Map("m" -> 3, "l" -> 23)),
    Map("a" -> Map("m" -> 4, "l" -> 24))
)

I want the result:

Map(1->21,2->22,3->23,4->24)

What I have so far is:

val tt = (for {
  (k,v) <- t
  newKey = v("m")
  newVal = v("l")
} yield Map(newKey -> newVal)).flatten.toMap

But this does not type check so Im missing some basic understanding since I cant understand why not?

My questions are:

  1. Why is my code faulty?
  2. What would be the most idiomatic way to do the transformation I want?
2

2 Answers

2
votes

You've got List[Map[...]], not Map[...] so you want to unpack that first.

val tt = (for {
  map <- t
  (k, v) <- map
} ...)
0
votes
  t
   .iterator
   .flatMap(_.values)
   .map { v => v("m") -> v("l") }
   .toMap