0

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 Answers 2

2

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

val tt = (for {
  map <- t
  (k, v) <- map
} ...)
Sign up to request clarification or add additional context in comments.

Comments

0
  t
   .iterator
   .flatMap(_.values)
   .map { v => v("m") -> v("l") }
   .toMap

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.