How to merge two maps into one with keys from the first map and merged values?

前端 未结 3 887
暗喜
暗喜 2021-01-14 07:10

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         


        
相关标签:
3条回答
  • 2021-01-14 07:43

    Update: I don't really understand what your edit about Iterables means, or the error in your comment, but here's a complete working example with Strings and Floats:

    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.

    0 讨论(0)
  • 2021-01-14 07:45
    val keys = map1.keySet & map2.keySet
    val map3 = keys.map(k => k -> (map1(k) ++ map2(k)))
    
    0 讨论(0)
  • 2021-01-14 08:03

    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.

    0 讨论(0)
提交回复
热议问题