You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Groovy中如何通过点路径字符串向已有Map添加嵌套键

在Groovy中通过点路径字符串向嵌套Map添加键值对

场景说明

现有两个JSON转换而来的Groovy Map:

// MAP A
[a: [b: true, c: [d: 'Hello']]]

// MAP B
[a: [c: [e: 'Sir']]]

需要将MAP B中a.c.e对应的值添加到MAP A的对应位置,最终得到合并后的Map:

[a: [b: true, c: [d: 'Hello', e: 'Sir']]]

已知目标键的点路径字符串为a.c.e,如何通过该路径实现嵌套键的添加?

解决方案

1. 通用工具方法实现路径解析与添加

编写一个可复用的方法,拆分点路径并逐层遍历Map,自动创建不存在的中间层级,最终完成键值添加:

// 向嵌套Map中添加指定路径的键值对
def addNestedKey(Map targetMap, String keyPath, Object value) {
    def keys = keyPath.split(/\./)
    def currentLayer = targetMap
    
    // 遍历到倒数第二个层级,确保路径存在
    for (int i = 0; i < keys.length - 1; i++) {
        def currentKey = keys[i]
        if (!currentLayer.containsKey(currentKey)) {
            currentLayer[currentKey] = [:]
        }
        currentLayer = currentLayer[currentKey]
    }
    
    // 设置最后一个键的值
    currentLayer[keys[-1]] = value
}

2. 结合源Map完成合并操作

如果需要从MAP B中提取对应路径的值再添加到MAP A,可以配合一个获取嵌套值的方法:

// 从嵌套Map中获取指定路径的值
def getNestedValue(Map sourceMap, String keyPath) {
    def keys = keyPath.split(/\./)
    def currentLayer = sourceMap
    
    for (def key : keys) {
        if (!currentLayer.containsKey(key)) {
            return null
        }
        currentLayer = currentLayer[key]
    }
    return currentLayer
}

// 执行合并逻辑
def mapA = [a: [b: true, c: [d: 'Hello']]]
def mapB = [a: [c: [e: 'Sir']]]
def targetPath = 'a.c.e'

def targetValue = getNestedValue(mapB, targetPath)
addNestedKey(mapA, targetPath, targetValue)

println mapA
// 输出结果: [a:[b:true, c:[d:Hello, e:Sir]]]

3. Groovy特性简化写法

利用Groovy的inject特性,用更简洁的代码实现相同逻辑:

def mapA = [a: [b: true, c: [d: 'Hello']]]
def path = 'a.c.e'
def value = 'Sir'

def parts = path.split(/\./)
// 逐层遍历路径,自动创建不存在的中间层级
def parent = parts[0..-2].inject(mapA) { m, k -> m[k] ?: (m[k] = [:]) }
parent[parts[-1]] = value

println mapA

内容的提问来源于stack exchange,提问作者Sharas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 21:57:10