Home > Software design >  Groovy iterate over Arraylist of Maps
Groovy iterate over Arraylist of Maps

Time:11-03

I'm working in a declarative pipeline, and I have a string that looks like this:

'[[key_A:value1, key_B:value2, key_C:value3],[key_A:value4, key_B:value5, key_C:value6],[key_A:value7, key_B:value8, key_C:value9]]'

Can I get help on what the quickest way is to turn the string into a map, then retrieve values of each map in the arraylist?

CodePudding user response:

Can I get help on what the quickest way is to turn the string into a map, then retrieve values of each map in the arraylist?

The input string you provide doesn't look like a map, it looks like a list of map. You can turn the string into a list of map using something like this (notice that the values here are quoted so they are strings, otherwise you would have to provide variables for value1, value2 etc):

    def inputString = '[[key_A:"value1", key_B:"value2", key_C:"value3"],[key_A:"value4", key_B:"value5", key_C:"value6"],[key_A:"value7", key_B:"value8", key_C:"value9"]]'
    def inputList = Eval.me (inputString)

Then you could iterate over that list to retrieve the maps and do whatever you want to do with the values in the maps:

    def inputString = '[[key_A:"value1", key_B:"value2", key_C:"value3"],[key_A:"value4", key_B:"value5", key_C:"value6"],[key_A:"value7", key_B:"value8", key_C:"value9"]]'
    def inputList = Eval.me (inputString)

    inputList.each { Map m ->
        println m.values()
    }
  • Related