Groovy Map of Lists into List of Maps
dictionary, groovy, list
Solution
Here's another way to do it, that I think is less obscure while still being fairly concise:
def ml = [a: ["c","d"], b: ["e","f"]]
// Create an empty list that creates empty maps as needed
def lm = [].withDefault{ [:] }
ml.each{ k, values ->
[values].flatten().eachWithIndex { value, index ->
lm[index][k] = value
}
}
assert lm == [[a:"c", b:"e"], [a:"d", b:"f"]]
If you don't want or cannot use `withDefault` (because you don't want the list to grow automatically), then this works too:
def ml = [a: ["c","d"], b: ["e","f"]]
def lm = []
ml.each{ k, values ->
[values].flatten().eachWithIndex { value, index ->
lm[index] = lm[index] ?: [:]
lm[index][k] = value
}
}
assert lm == [[a:"c", b:"e"], [a:"d", b:"f"]]
Edit: Added code to handle strings not contained within a list.
Note, the given trick (`[values].flatten().eachWithIndex{...}`) is not necessarily very efficient. If speed is essential, then using this would be slightly faster at the expense of readability:
(values instanceof List ? values : [values]).eachWithIndex{...}
Problem
So essentially I have something like this: ``` [a: ["c","d"], b: ["e","f"]] ``` The amount of items in each list is arbitrary. If there is only one item the list is no longer a list and it is a string. I want to turn it into: ``` [ [a:"c", b:"e"], [a:"d",b:"f"] ] ``` I don't really care if the solution uses Groovy methods or not. Thanks for your help!