How can I create a new map from two maps of maps so that the resulting map only includes matches where keys are the same and combines the internal maps.
Iter
Update: I don't really understand what your edit about Iterable
s means, or the error in your comment, but here's a complete working example with String
s and Float
s:
val map1: Map[Int, Map[String, Float]] = Map(
1 -> Map("key1" -> 1.0F),
2 -> Map("key2" -> 2.0F),
3 -> Map("key3" -> 3.0F))
val map2: Map[Int, Map[String, Float]] = Map(
1 -> Map("key11" -> 11.0F),
3 -> Map("key33" -> 33.0F),
4 -> Map("key44" -> 44.0F),
5 -> Map("key55" -> 55.0F))
val map3: Map[Int, Map[String, Float]] = for {
(k, v1) <- map1
v2 <- map2.get(k)
} yield (k, v1 ++ v2)
Update in response to your question below: it doesn't make a lot of sense to have a list of maps, each containing a single mapping. You can very easily combine them into a single map using reduceLeft
:
val maps = List(
Map(1216 -> Map("key1" -> 144.0F)),
Map(1254 -> Map("key2" -> 144.0F)),
Map(1359 -> Map("key3" -> 144.0F))
)
val bigMap = maps.reduceLeft(_ ++ _)
Now you have one big map of integers to maps of strings to floats, which you can plug into my answer above.