我想从嵌套地图中获取展平地图。展平的地图必须用点分隔键。
例如,
def map = ['environment':'production', 'classes':['nfs-server':['exports':['/srv/share1', '/srv/share3']]], 'parameters':'null']
预期输出
[environment:'production', classes.nfs-server.exports:['/srv/share1', '/srv/share3'], parameters:'null']
我环顾四周,想出了以下使用递归的代码片段。这是代码
def Map<String, String> getNestedMapKeys(Map map, String keyPrefix = '') {
def result = [:]
map.each { key, value ->
if (value instanceof Map) {
result += getNestedMapKeys(value, keyPrefix += "$key.")
} else {
String finalKey = "$keyPrefix$key"
// need to wrap in parenthesis because it's a variable
result << [(finalKey): value]
}
}
result
}
运行它的输出是
[environment:'production', classes.nfs-server.exports:['/srv/share1', '/srv/share3'], classes.parameters:'null']
因此,嵌套地图后处理的密钥仍保留前缀。在这种情况下,&#39; classes.parameters&#39;应该只是参数&#39;。任何修复它的帮助表示赞赏。感谢。
答案 0 :(得分:1)
想出来。需要在主地图处理嵌套地图结束时重置'keyPrefix'变量。
def Map<String, String> getNestedMapKeys(Map map, String keyPrefix = '') {
def result = [:]
map.each { key, value ->
if (value instanceof Map) {
print 'key prefix is ' + keyPrefix
result += getNestedMapKeys(value, keyPrefix += "$key.")
keyPrefix = ''
} else {
String finalKey = "$keyPrefix$key"
// need to wrap in parenthesis because it's a variable
result << [(finalKey): value]
}
}
result
}
答案 1 :(得分:1)
这个怎么样?
def flattenMap(Map map) {
map.collectEntries { k, v ->
v instanceof Map ?
flattenMap(v).collectEntries { k1, v1 ->
[ "${k}.${k1}": v1 ]
}
:
[ (k): v ]
}
}