How to include all indexes of a string array into one line in Groovy (Or Java)

If you have the answer in java, it will be similar enough to translate it. Thank you in advance for your time.

I’m trying to take all strings within an array and call them in one docker line to create a single tar file. I’m not confused as to how to create the tar file. It should look something like the following:

sh "docker save [image1]:tag [image2]:tag etc... > docker.tar"

My issue is that the images that I need to tar are listed in the following format:

myMap = [
        "StringIndex0": ["keyword": "image0", "unrelatedKeyword": "sentence0"],
        "StringIndex1": ["keyword": "image1", "unrelatedKeyword": "sentence1"],
        "StringIndex2": ["keyword": "image2", "unrelatedKeyword": "sentence2"],
        ]

I can’t do a for loop like the following:

for (index in myMap) {
    for (img in myMap[index]['keyword']){
         sh "docker save ${img}:tag > docker.tar"
    }
}

because that’ll create docker save [image1:tag] > docker.tar and docker save [image2:tag] > docker.tar individually which will overwrite each other. I am looking for a solution to be able to tar all the images at once.

I am not sure concatenating will work as it may come out looking incorrectly:

docker save image1 image2 imag3:tag > docker.tar

And I’m hoping for an answer that will work with any number of StringIndexes in my array so I’m not hardcoding it like this:

AllKeywords = ""
    for (index in myMap) {
       for (img in myMap[index]['keyword']) {
           AllKeywords += "${img}"
 
    }
}
sh "docker save AllKeywords[0]:tag AllKeywords[1]:tag > docker.tar"

Because essentially then I could just do:

sh "docker save myMap[StringIndex0]['keyword']:tag myMap[StringIndex1]['keyword']:tag > docker.tar"

Which would not account for anymore StringIndexes as they become added.

I am new to SO so if my question is unclear at all, please let me know and I will do my best to fix it.

Answer

Presuming that your map is in fact a map of maps, here’s one option:

String saveTargets = map.values().collect { "${it['keyword']}:tag" }.join(' ')

sh "docker save $saveTargets > docker.tar"

If your tag is in fact parameterized, just replace it with $tag.

(As this is Groovy, there are a number of alternatives, but this should get you there.)