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

前端 未结 3 888
暗喜
暗喜 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.

提交回复
热议问题