# Conversión de una lista de mapas en un solo mapa en scala [duplicado]

Scala How to create a new map from two other maps

I have the following list of maps that I need to convert to a single map. What is the best way to do this?

The list of maps are of type:

``````Iterable[Map[String, Map[String,Float]]
``````

Ejemplo:

``````val list1 = List(Map(1216 -> Map(key1 -> 144.0)),
Map(1253 -> Map(key1 -> 144.0)),
Map(1359 -> Map(key1 -> 144.0))

val list2 = List(Map(1216 -> Map(key2 -> 148.0)),
Map(1200 -> Map(key2 -> 144.0)),
Map(1359 -> Map(key2 -> 144.0))
``````

I want a resulting map that would be

``````val map3 = Map(
1216 -> Map(key1 -> 1440, key2 -> 148.0),
1359 -> Map(key1 -> 1440, key2 -> 144.0))
``````

gracias

preguntado el 09 de marzo de 12 a las 22:03

## 2 Respuestas

First, find all the keys that should be in your new map, which are keys that exist in both of your lists of maps (I'm assuming):

``````val keys = list1.map(_.keySet).reduceLeft(_ | _) & list2.map(_.keySet).reduceLeft(_ | _)
``````

Then pick out the values of all of those keys:

``````val alllist = list1 ++ list2
val map3 = keys.map(k => k -> alllist.flatMap(_ get k).reduceLeft(_ ++ _))
``````

Not super-efficient, but it gets the job done.

respondido 09 mar '12, 22:03

If I got it right, something like this will do the trick:

``````scala> import scalaz._
import scalaz._

scala> import Scalaz._
import Scalaz._

scala> list1 ++ list2
res2: List[scala.collection.immutable.Map[Int,scala.collection.immutable.Map[java.lang.String,Double]]] = List(Map(1216 -> Map(key1 -> 144.0)), Map(1253 -> Map(key1 -> 144.0)), Map(1359 -> Map(key1 -> 144.0)), Map(1216 -> Map(key2 -> 148.0)), Map(1200 -> Map(key2 -> 144.0)), Map(1359 -> Map(key2 -> 144.0)))

scala> .foldLeft(Map[Int,Seq[Map[String,Double]]]()) { case (acc, v) =>
| v.mapValues(Seq(_)) |+| acc
| }
res8: scala.collection.immutable.Map[Int,Seq[Map[String,Double]]] = Map(1216 -> List(Map(key2 -> 148.0), Map(key1 -> 144.0)), 1253 -> List(Map(key1 -> 144.0)), 1359 -> List(Map(key2 -> 144.0), Map(key1 -> 144.0)), 1200 -> List(Map(key2 -> 144.0)))

scala> .map { case(i, m) => (i, m reduce (_ ++ _)) }
res11: scala.collection.immutable.Map[Int,Map[String,Double]] = Map(1216 -> Map(key2 -> 148.0, key1 -> 144.0), 1253 -> Map(key1 -> 144.0), 1359 -> Map(key2 -> 144.0, key1 -> 144.0), 1200 -> Map(key2 -> 144.0))y2 -> 148.0)), Map(1200 -> Map(key2 -> 144.0)), Map(1359 -> Map(key2 -> 144.0)))
``````

respondido 10 mar '12, 10:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.