如何在groovy中创建另一个字段映射?

如何在groovy中创建另一个字段映射?,groovy,Groovy,我有这张地图: @Field def images = [ [name: 'image-1', shouldBuild: "false"], [name: 'image-2', shouldBuild: "false"], [name: 'image-3', shouldBuild: "false"] ] 在函数中,我检查这些图像名称是否包含在文本文件中 如果包含任何图像,我需要创建一个仅包含这些特定图像的新字段映射 因此,假设只包含image-

我有这张地图:

@Field
def images = [
        [name: 'image-1', shouldBuild: "false"],
        [name: 'image-2', shouldBuild: "false"],
        [name: 'image-3', shouldBuild: "false"]
]
在函数中,我检查这些图像名称是否包含在文本文件中

如果包含任何图像,我需要创建一个仅包含这些特定图像的新字段映射

因此,假设只包含image-1,我希望新的字段映射注意shouldBuild中的更改为true:

@Field
def imagesChanged = [
        [name: 'image-1', shouldBuild: "true"]
]
这就是我到目前为止所做的:

for (imageMap in images) {
    def shouldBuild = imageMap.get('shouldBuild')
    def image = imageMap.get('name')

    if (diff.any { el -> el.contains(image) }) {
      shouldBuild = "true"
    }
这可以在images字段中将shouldBuild设置为true,而不是在imagesChanged字段中。我应该怎么做?

我假设diff是一个有效图像名称数组

您只需要使用新的映射构建新阵列

def images = [
        [name: 'image-1', shouldBuild: "false"],
        [name: 'image-2', shouldBuild: "false"],
        [name: 'image-3', shouldBuild: "false"]
]
def diff = ['image-2']

def imagesChanged = []
for (imageMap in images) {
    def image = imageMap.get('name')

    if (diff.any { el -> el.contains(image) }) {
      //imageMap + [shouldBuild: "true" ]  --> creates a new map with `shouldBuild` changed
      imagesChanged.add(imageMap + [shouldBuild: "true" ])
    }
}

println images
println imagesChanged
仅供参考:这段代码可能更符合groovy

def images = [
        [name: 'image-1', shouldBuild: "false"],
        [name: 'image-2', shouldBuild: "false"],
        [name: 'image-3', shouldBuild: "false"]
]
def diff = ['image-2']

def imagesChanged = images.findAll{ i-> i.name in diff }.collect{ i->
    i+[shouldBuild:"true"]
}

println images
println imagesChanged
正确的单行图像.findResults{i->i.name在diff?i+[shouldBuild:true]:null}