【问题标题】:Groovy map mergeGroovy 地图合并
【发布时间】:2020-05-11 23:28:48
【问题描述】:

问题: 如何合并两个具有相同键集但值不同的 groovy 映射。

例子:

Map one = [ 'a': ['foot':'ball'],
            'b': 'cricket',
            'c': 'tennis'
           ]

Map two = ['a': ['basket':'ball']]

我想要的输出是:

Map three = [ 'a': ['foot':'ball', 
                    'basket': 'ball'],
                'b': 'cricket',
                'c': 'tennis'
               ]

如上所示,它需要选择任何匹配的键并合并这些键的值并生成组合映射。

提前致谢。

【问题讨论】:

  • 您想如何处理碰撞,例如,在其中一张地图中将“脚”映射到“手”?
  • 如果脚映射到手,则后者优先。所以地图二优先。
  • 这能回答你的问题吗? Merge maps with recursive nested maps in Groovy

标签: groovy


【解决方案1】:

可能有一个更短的方法可以做到这一点,但它非常简洁:

   Map three = [:]
   (one.entrySet() + two.entrySet()).each { entry -> 
       three[entry.key] = three.containsKey(entry.key) ? [:] << three[entry.key] << entry.value : entry.value 
   }

   println three

并产生预期的结果:

[a:[foot:ball, basket:ball], b:cricket, c:tennis]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-09
    • 2012-10-30
    • 1970-01-01
    • 1970-01-01
    • 2017-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多