user3139545 user3139545 - 1 month ago 8
Scala Question

Convert List[Map[String,Map[String,Int]]] to Map[Int,Int] in Scala

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?


Answer

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

val tt = (for {
  map <- t
  (k, v) <- map
} ...)