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

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

提交回复
热议问题