在Scala中递归合并嵌套Map [英] Recursive merge nested Map in Scala

查看:47
本文介绍了在Scala中递归合并嵌套Map的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些嵌套的地图,例如:

I have some nested maps like:

val map1 = Map("key1"->1, "key2"->Map("x"->List(1,2)))
val map2 = Map("key3"->3, "key2"->Map("y"->List(3,4)))

我想将它们合并以获得类似的结果图;

And I want to merge them to obtain the result map like;

val res = Map("key1"->1, "key2"->Map("x"->List(1,2), "y"->List(3,4)), "key3"->3)

因此,嵌套地图也应合并.映射和嵌套映射的类型可以假定为Map [String,Any].如果两个映射具有冲突键(例如,同一键的值不同,只是该值是嵌套映射),则认为是一个例外.

So nested maps should also be merged. The type of the maps and nested maps can be assumed as Map[String, Any]. It's considered an exception if the two maps have conflict keys (eg. values of the same key are different, except that the value is a nested map).

是否有一些优雅的解决方案?谢谢!

Is there some elegant solution to this? Thanks!

推荐答案

有关以下内容:

type MapType = Map[String, Any]

def merge(map1 : MapType, map2 : MapType) = (map1.keySet ++ map2.keySet)
  .map(key => key -> mergeValues(map1.get(key), map2.get(key)))
  .toMap

private def mergeValues(o1 : Option[Any], o2 : Option[Any]) = (o1, o2) match {
  case (Some(v1 : MapType), Some(v2 : MapType)) => v1 ++ v2
  case _ => (o1 orElse o2).get
}

您可以修改 mergeValues 函数以支持其他情况(即,相同的键指向2个非映射值的情况-此刻将返回第一个值).

You can modify the mergeValues function to support additional cases (i.e. situation when the same key points to 2 values which are not maps - at the moment will return the first of the values).

这篇关于在Scala中递归合并嵌套Map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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