How to combine two cards into one with the keys from the first card and the combined values?

How to create a new card from two card cards so that the resulting card only includes matches where the keys are the same and combines the inner cards.

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 to be as follows:

Map(
  1 -> Map(key1 -> val1, key11 -> val11), 
  3 -> Map(key3 -> val3, key33 -> val33)
)

      

+3


source to share


3 answers


Update: I don't quite understand what your change about Iterable

or the error in your comment means , but here's a complete working example with String

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 much sense to have a list of maps, each containing one mapping. You can easily combine them into one 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(_ ++ _)

      

You now have one big integer map to float string maps that you can include in my answer above.

+9


source


val keys = map1.keySet & map2.keySet
val map3 = keys.map(k => k -> (map1(k) ++ map2(k)))

      



+6


source


I've been playing around with something similar to converting Seq(Map("one" -> 1), Map("two" -> 2))

to Map("one" -> 1, "two" -> 2)

.

I looked at the previous answers and thought it was too complicated. After playing around a bit, I found this solution works and it's 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 cards are automatically filtered out.

0


source







All Articles