I have a map in groovy where each item has multiple values that I need to use in a loop. The number of values is fixed, so could be stored in a list/array, tuple - does not matter.
Example, I tried:
def routemap = [ One: ['Berlin','Hamburg'], Two: ['London','Paris'], Three: ['Rome','Barcelona']]
routemap.each { route, startend ->
println "Route: $route"
println "Start: $startend[0] End: $startend[1]"
}
This does not provide the desired result, the list index does not work.
Route: One
Start: [Berlin, Hamburg][0] End: [Berlin, Hamburg][1]
Route: Two
Start: [London, Paris][0] End: [London, Paris][1]
Route: Three
Start: [Rome, Barcelona][0] End: [Rome, Barcelona][1]
Also I am wondering if there is a better, more elegant way to do it? Is there a way to assign two values (or a pair or tuple like in Python) instead of "startend" in the loop?
You should put $startend[index]
in the curly brackets, like ${startend[0]}
. So your code will look like that:
def routemap = [ One: ['Berlin','Hamburg'], Two: ['London','Paris'], Three: ['Rome','Barcelona']]
routemap.each { route, startend ->
println "Route: $route"
println "Start: ${startend[0]} End: ${startend[1]}" // here is the change
}