0

Eg. Map[Map[String,Int],Int] I need to convert it into Map[String,Int] i.e Int in value part of inner map is replaced with Int in value part of outer map.

For example:

val innerMap = Map("a"->1)
val outerMap = Map(innerMap, 2)

Required result:

resultMap = Map("a"->2)
3
  • 1
    Consider: Map(Map("a"->1)->11,Map("a"->2)->22) Should the result be "a"->11 or "a"->22? Commented Jan 24, 2019 at 5:40
  • 1
    yes that which @jwvh asked and also what if we have Map(Map("a" -> 1, "b" -> 2) -> 3))? Commented Jan 24, 2019 at 5:42
  • Map("a" -> 3 , "b" -> 3) Commented Jan 24, 2019 at 5:46

3 Answers 3

3

Even though you haven't answered my question about duplicate String values, I'm going to guess that what you want is something like this.

val mmsii :Map[Map[String,Int],Int] =
  Map(Map("a"->1)->11,Map("b"->2)->22)

mmsii.flatMap{case (m,v) => m.keys.map(_ -> v)}

Or, using the sometimes friendlier for comprehension:

for {
  (m,v) <- mmsii
  (k,_) <- m
} yield k->v

Keep in mind, if there are duplicate String keys then only one String->Int pair will be retained and the others will be lost.

Sign up to request clarification or add additional context in comments.

Comments

0

Pretty much the same as @jwvh's solution, just a little more explicit

val nestedMap: Map[Map[String, Int], Int] = Map(
  Map("k1" -> 1) -> 11,
  Map("k2" -> 2, "k3" -> 3) -> 22
)

val unnestedMap: Map[String, Int] = nestedMap.flatMap { (outerTuple: (Map[String, Int], Int)) =>
  val innerMap: Map[String, Int] = outerTuple._1
  val commonVal: Int = outerTuple._2
  innerMap.map { (innerTuple: (String, Int)) =>
    (innerTuple._1 -> commonVal)
  }
}
print(unnestedMap)

Comments

0

You can leverage this solution to your problem

    val anotherMap = Map(Map("a" -> 1) -> 10, Map("b" -> 2) -> 11, Map("c" -> 3) -> 12)

    anotherMap.flatMap {
  case (keyMap, value) =>
    keyMap map {
      case (k, _) => Map(k -> value)
    }
}

// res0: scala.collection.immutable.Iterable[scala.collection.immutable.Map[String,Int]] = List(Map(a -> 10), Map(b -> 11), Map(c -> 12))

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.