Reputation: 2908
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.
Iterable[Map[String, Map[String,Float]]
Example:
val map1 = Iterable(Map(
1 -> Map(key1 -> val1),
2 -> Map(key2 -> val2),
3 -> Map(key3 -> val3)
))
val map2 = Iterable(Map(
1 -> Map(key11 -> val11),
3 -> Map(key33 -> val33),
4 -> Map(key44 -> val44),
5 -> Map(key55 -> val55)
))
I want the resulting map be as follows:
Map(
1 -> Map(key1 -> val1, key11 -> val11),
3 -> Map(key3 -> val3, key33 -> val33)
)
Upvotes: 3
Views: 2874
Reputation: 5017
I have been playing with something similar to convert a Seq(Map("one" -> 1), Map("two" -> 2))
to Map("one" -> 1, "two" -> 2)
.
I have been looking at previous answers and thought it was too difficult. After playing a bit I found that this solution works and it easy:
val seqOfMaps = Seq(Map("one" -> 1), Map("two" -> 2))
seqOfMaps: Seq[scala.collection.immutable.Map[String,Int]] = List(Map(one -> 1), Map(two -> 2))
val allInOneMap = seqOfMaps.flatten.toMap
allInOneMap: scala.collection.immutable.Map[String,Int] = Map(one -> 1, two -> 2)
The advantage of this approach is that possible empty maps automatically get filtered out.
Upvotes: 0
Reputation: 139038
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.
Upvotes: 10
Reputation: 167891
val keys = map1.keySet & map2.keySet
val map3 = keys.map(k => k -> (map1(k) ++ map2(k)))
Upvotes: 6