Search code examples
listscalamapsintersect

Scala How to Intersect Maps of types Map[String, Double] inside a List of: List[Map[String, Double]]


So I have a list of maps: List[Map[String, Double]]. An example of it would be:

List(Map("A" -> 1.1, "B" -> 2.5, "E" -> 3.5, "C" -> 1.6, "D" -> 0.9), 
        Map("A" -> 0.8, "C" -> 2.1, "D" -> 2.8), 
        Map("C" -> 2.2, "D" -> 2.9, "A" -> 3.4), 
        Map("B" -> 0.4, "D" -> 1.8, "E" -> 0.234, "A" -> 3.7))

What I want to do is to get the intersect of all of the maps together so then it looks like:

   For example, for A: (1.1 + 0.8 + 3.4 + 3.7)/4 = 2.25
                for D: (0.9 + 2.8 + 2.9 + 1.8)/4 = 2.1

   List(Map("A" -> 2.25,"D" -> 2.1))

Is there a way to get the intersected list of map above using built in functions only? The values are the average of all of the keys in the four maps combined.


Solution

  • Try first using reduce to keep only duplicate keys and add up all the values, and then use mapValues to get the mean:

    val maps = List(...)
    
    val intersected = maps
      .reduce { (m1, m2) =>
        m1.keySet.intersect(m2.keySet).map(key => (key, m1(key) + m2(key))).toMap
      }
      .view
      .mapValues(_ / maps.size)
      .toMap
    

    Scastie

    This question is similar.