Scala:如何合并地图集合 [英] Scala: how to merge a collection of Maps

查看:128
本文介绍了Scala:如何合并地图集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Map [String,Double]列表,我想将它们的内容合并成一个Map [String,Double]。我应该怎么用惯用的方法呢?我想我应该能够做到这一点。例如:

  val newMap = Map [String,Double]()/:listOfMaps {(accum,m)=> ...} 

此外,我想以通用的方式处理关键的冲突。也就是说,如果我添加了一个已经存在的地图的键,我应该可以指定一个返回一个Double(在这种情况下)的函数,并获取该键的现有值,再加上我要添加的值。如果地图中的关键字不存在,那么只需添加它的值并保留其值。



在我的具体情况下,我想构建一个Map [String ,Double],以便如果地图已经包含一个键,则Double将被添加到现有的地图值。



我正在使用可变地图代码,但是如果可能,我对更通用的解决方案感兴趣。

解决方案

b
$ b

  def mergeMap [A​​,B](ms:List [Map [A​​,B]])(f:(B,B)=> B(A,B)= 
(映射[A,B]()/:(for(m a +(if(a.contains(kv._1))kv._1 - > f(a(kv._1),kv._2)else kv)
}

val ms = List(Map(hello - > 1.1,world - > 2.2),Map(goodbye - > 3.3,hello - > 4.4))
val mm = mergeMap(ms)((v1,v2)=> v1 + v2)

println(mm)// prints Map(hello - > 5.5,world - > 2.2,再见 - > 3.3)

它在2.7.5和2.8.0中都有效。


I have a List of Map[String, Double], and I'd like to merge their contents into a single Map[String, Double]. How should I do this in an idiomatic way? I imagine that I should be able to do this with a fold. Something like:

val newMap = Map[String, Double]() /: listOfMaps { (accumulator, m) => ... }

Furthermore, I'd like to handle key collisions in a generic way. That is, if I add a key to the map that already exists, I should be able to specify a function that returns a Double (in this case) and takes the existing value for that key, plus the value I'm trying to add. If the key does not yet exist in the map, then just add it and its value unaltered.

In my specific case I'd like to build a single Map[String, Double] such that if the map already contains a key, then the Double will be added to the existing map value.

I'm working with mutable maps in my specific code, but I'm interested in more generic solutions, if possible.

解决方案

How about this one:

def mergeMap[A, B](ms: List[Map[A, B]])(f: (B, B) => B): Map[A, B] =
  (Map[A, B]() /: (for (m <- ms; kv <- m) yield kv)) { (a, kv) =>
    a + (if (a.contains(kv._1)) kv._1 -> f(a(kv._1), kv._2) else kv)
  }

val ms = List(Map("hello" -> 1.1, "world" -> 2.2), Map("goodbye" -> 3.3, "hello" -> 4.4))
val mm = mergeMap(ms)((v1, v2) => v1 + v2)

println(mm) // prints Map(hello -> 5.5, world -> 2.2, goodbye -> 3.3)

And it works in both 2.7.5 and 2.8.0.

这篇关于Scala:如何合并地图集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆