Search code examples
listgroovyelementremoveall

Groovy -- how would I remove an element from a list based on the content of the element?


I'm working on a groovy script for Jira -- I'm collecting a list of comments from an issue, and storing the username of the last comment.

Example:

import com.atlassian.jira.component.ComponentAccessor
def commentManager = ComponentAccessor.getCommentManager()
def comments = commentManager.getComments(issue)
if (comments) {
comments.last().authorUser
}

Occasionally, I don't want to store the username (if it belongs to a predefined role). Basically, I want to check the comments first, and remove any comments from my list that meet my criteria, then end by calling last().authorUser. Something like:

comments.each {
if (it.authorUser.toString().contains(user.toString())) {    
// Here is where I'd want to remove the element from the list**
}
}
comments.last().authorUser  // then store the last element as my most recent comment. 

Make sense? I am new to Groovy -- so I fully suspect a bunch of head-scratching. Most of the examples I ran into dealt with numeric checking... kinda stumped.


Solution

  • You could use Collection.removeAll(): it modifies the collection by removing elements that are matched by the closure condition passed.

    comments.removeAll {
        it.authorUser.toString().contains(user.toString())
    }
    comments.last().authorUser