我想从嵌套 map 中获取展平的 map 。展平后的映射必须用点分隔键。
例如,
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']
因此,在嵌套映射之后处理的键仍然保留前缀。在这种情况下,“classes.parameters”应该只是“parameters”。任何修复它的帮助都会受到赞赏。谢谢。
最佳答案
想通了。需要在处理主 map 中的嵌套 map 结束时重置“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
}
关于java - 从 groovy 中的嵌套映射返回一维映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45046231/