groovy listmap拍平成map flattenedMap重名的key都被覆盖了怎么办
如果在拍平过程中遇到重名的key,可以采取以下几种处理方式:
- 保留最后一个值:当遇到重名的key时,只保留最后一个值,其他重名的值都被覆盖。
def list = [
[name: "John", age: 25],
[name: "Alice", age: 30],
[name: "John", age: 35]
]
def flattenedMap = [:]
list.each { map ->
map.each { key, value ->
flattenedMap[key] = value
}
}
println flattenedMap
输出结果:
[name:John, age:35]
- 保留所有值:当遇到重名的key时,将所有的值保存到一个列表中。
def list = [
[name: "John", age: 25],
[name: "Alice", age: 30],
[name: "John", age: 35]
]
def flattenedMap = [:]
list.each { map ->
map.each { key, value ->
if (flattenedMap.containsKey(key)) {
flattenedMap[key] << value
} else {
flattenedMap[key] = [value]
}
}
}
println flattenedMap
输出结果:
[name:[John, Alice], age:[25, 30, 35]]
- 保留所有值,并使用索引作为后缀:当遇到重名的key时,将所有的值保存到一个列表中,并使用索引作为后缀来区分不同的值。
def list = [
[name: "John", age: 25],
[name: "Alice", age: 30],
[name: "John", age: 35]
]
def flattenedMap = [:]
list.eachWithIndex { map, index ->
map.each { key, value ->
if (flattenedMap.containsKey(key)) {
flattenedMap[key + index] = value
} else {
flattenedMap[key] = value
}
}
}
println flattenedMap
输出结果:
[name:John, age:25, name1:Alice, age1:30, name2:John, age2:35]
你可以根据具体的需求选择适合的处理方式
原文地址: http://www.cveoy.top/t/topic/iUBx 著作权归作者所有。请勿转载和采集!