简体   繁体   English

Scala - 将地图列表展平到地图

[英]Scala - Flatten a List of Maps to Map

I need to map a key to a map inside a list in Scala.我需要将一个键映射到 Scala 列表中的映射。 In other words, I need to go from here:换句话说,我需要从这里开始:

  Map(k1 -> List(Map(k2 -> v2)))

And get this:得到这个:

  Map(k1 -> Map(k2 -> v2))

This stuff is working but I am looking for something more efficient.这些东西正在起作用,但我正在寻找更有效的东西。

  val m1 = Map("k1" -> List(Map("k2" -> "v2")))
  val m2 = m1("k1").flatten.toMap
  val m3 = Map("k1" -> m2)

Any thoughts?有什么想法吗?

Thanks in advance.提前致谢。

Like @Luis Miguel Mejía Suárez said it is mostly something like就像@Luis Miguel Mejía Suárez 说的那样

val maps = Map(k1 -> List(Map(k2 -> v2)))
def flattenMaps[K, V]: List[Map[K, V]] => Map[K, V] = ???
maps.mapValues(flattenMaps).toMap

The devil is in the details of your flattening logic:问题在于你的扁平化逻辑的细节:

// assumes that list always of size 1, loses random elements if bigger, blows up if size=0
def flattenMaps[K, V]: List[Map[K, V]] => Map[K, V] = _.head

// last wins
def flattenMaps[K, V]: List[Map[K, V]] => Map[K, V] = _.foldLeft(Map.empty[K, V]) {
  (bigMap, map) => bigMap ++ map
}

// first wins
def flattenMaps[K, V]: List[Map[K, V]] => Map[K, V] = _.foldLeft(Map.empty[K, V]) {
  (bigMap, map) => map ++ bigMap
}

// if you want to optimize for some reason, you can use builder instead
def flattenMaps[K, V]: List[Map[K, V]] => Map[K, V] = _.foldLeft(Map.newBuilder[K, V]) {
  (builder, map) =>
     builder ++= map
     builder
}.result

// or basically any other logic that makes sense and is defined for any input that type-checks

You should define some correct behavior in case your list will have more than one element (or none), otherwise you might be surprised one day if you'll forget about your assumptions.您应该定义一些正确的行为,以防您的列表包含多个元素(或没有),否则有一天您可能会忘记您的假设。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM