【发布时间】:2017-12-16 04:56:26
【问题描述】:
我想从嵌套地图中获取平面地图。扁平化地图的键必须用点分隔。
例如,
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']
我环顾四周,想出了以下使用递归的代码 sn-p。这是代码
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”应该只是“参数”。任何修复它的帮助表示赞赏。谢谢。
【问题讨论】:
标签: java dictionary groovy nested