I need to iterate this Map with all predecessor keys in groovy which I need to run through Jenkins.
a={b={c=1,d=2,e=3},r={p=4},q=5}
I want output like below and input is dynamic and format may vary. Please help since 1 week I am trying.
a:b:c=1
a:b:d=2
a:b:e=3
a:r:p=4
a:q=5
You can use a recursive function to achieve this result, here is an example:
def iterateMap(Map map, String prefix = "") {
map.each { key, value ->
if (value instanceof Map) {
iterateMap(value, "$prefix$key:")
} else {
println "a:$prefix$key=$value"
}
}
}
def a = [
b: [
c: 1,
d: 2,
e: 3
],
r: [
p: 4
],
q: 5
]
iterateMap(a)
In this code, the iterateMap function takes a map as input and an optional prefix string (initialized as an empty string). It iterates over each key-value pair in the map. If the value is itself a map, the function recursively calls itself with the nested map and the updated prefix ("$prefix$key:"). If the value is not a map, it prints the key-value pair in the desired format ("$prefix$key=$value").