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

206 views Asked by At

I have a collection of type ProjectComponent, I am using the following code to find an object in my collection with a specific name. Here is the code:

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

I am receiving the error Script function failed on Automation for Jira rule: UpdateExecutionSummary , file: SuperFeature/rest_superFeatureGenerator.groovy, error: groovy.lang.MissingPropertyException: No such property: it for class: SuperFeature.rest_superFeatureGenerator

But I have looked up tutorials and the it should work automatically even if it is not declared as you can see here:

enter image description here

3

There are 3 answers

0
chubbsondubs On BEST ANSWER

I think the first use of it should work fine. This is probably fine:

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

The second one is not defined.

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

If you want to grab the component you're after I might do this:

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

The problem is in this line: newComponent=it. You're using it in the scope, where it is not defined. The it variable is only "visible" inside the anyMatch {...} closure. What you need to do is, first, find the element, then assign. Here is the draft (using Java streams):

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

Although, I'd recommend using Groovy syntax:

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

I hope it will help.

0
منى On
 def found = newList.any { it.getName().equals(shortenedComponentName)}
                    log.warn("MOUNA CAMELIA found--"+found+"--")

                    if(found ){
                        newComponent=projectComponentManager.findByComponentName(newIssueproject.getId(), shortenedComponentName)
                    }