在 groovy 的对象集合中查找具有属性值的对象

Find an object with an attribute value within a collection of objects in groovy

提问人:Mouna Camelia Hammoudi 提问时间:9/26/2023 更新时间:9/28/2023 访问量:55

问:

我有一个 ProjectComponent 类型的集合,我正在使用以下代码在我的集合中查找具有特定名称的对象。代码如下:

 if(newIssueproject.getComponents().stream().anyMatch { it.getName().equals(shortenedComponentName)  }){
                        newComponent=it
   }

我收到错误脚本函数在 Automation for Jira 规则上失败:UpdateExecutionSummary ,文件:SuperFeature/rest_superFeatureGenerator.groovy,错误:groovy.lang.MissingPropertyException:没有此类属性:类:SuperFeature.rest_superFeatureGenerator

但是我已经查找了教程,即使它没有被声明,它也应该自动工作,正如你在这里看到的:

enter image description here

对象 变量 groovy scope scriptrunner-for-jira

评论

1赞 Andrej Istomin 9/27/2023
你为什么不使用 Groovy synthax?它有集合的方法,它比 Java 流更简洁、更有表现力。.find

答:

1赞 Andrej Istomin 9/27/2023 #1

问题出在这一行: . 您正在未定义的作用域中使用。该变量仅在闭包内“可见”。你需要做的是,首先,找到元素,然后分配。以下是草稿(使用 Java 流):newComponent=itititanyMatch {...}

def found = newIssueproject.getComponents().stream().filter { it.getName().equals(shortenedComponentName) }.findAny()
newComponent = found.orElseGet(null)

虽然,我建议使用 Groovy 语法:

def found = newIssueproject.getComponents().find { it.getName() == shortenedComponentName) }
if (found) {
    newComponent = found
}

我希望它会有所帮助。

评论

0赞 Mouna Camelia Hammoudi 9/27/2023
代码仍然错误,但它走在正确的轨道上,这是正确的代码def found = newList.any { it.getName().equals(shortenedComponentName)} log.warn("MOUNA CAMELIA found--"+found+"--") if(found ){ newComponent=projectComponentManager.findByComponentName(newIssueproject.getId(), shortenedComponentName) }
0赞 Mouna Camelia Hammoudi 9/27/2023 #2
 def found = newList.any { it.getName().equals(shortenedComponentName)}
                    log.warn("MOUNA CAMELIA found--"+found+"--")

                    if(found ){
                        newComponent=projectComponentManager.findByComponentName(newIssueproject.getId(), shortenedComponentName)
                    }
1赞 chubbsondubs 9/28/2023 #3

我认为第一次使用应该可以正常工作。这可能没问题:it

newIssueproject.getComponents().stream().anyMatch { 
   it.getName().equals(shortenedComponentName)  
})

第二个没有定义。

if(newIssueproject.getComponents().stream().anyMatch { it.getName().equals(shortenedComponentName)  }){
    newComponent=it   // it's me.  I'm the problem it's me.
}

如果你想抓住你所追求的组件,我可能会这样做:

newIssueProject.components.stream()
    .findFirst { it.name == shortedComponentName }
    .ifPresent { component ->
       // do something with it
    }