Groovy——如何根据元素的内容从列表中删除元素?

Ham*_*ich 4 groovy element list removeall

我正在为 Jira 编写一个 groovy 脚本——我正在收集某个问题的评论列表,并存储最后一条评论的用户名。

例子:

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

有时,我不想存储用户名(如果它属于预定义的角色)。基本上,我想首先检查评论,并从列表中删除符合我的条件的所有评论,然后通过调用last().authorUser 结束。就像是:

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. 
Run Code Online (Sandbox Code Playgroud)

合理?我是 Groovy 的新手——所以我完全怀疑这会让人头疼。我遇到的大多数例子都涉及数字检查......有点难住了。

Kai*_*nad 8

您可以使用Collection.removeAll():它通过删除与传递的闭包条件匹配的元素来修改集合。

comments.removeAll {
    it.authorUser.toString().contains(user.toString())
}
comments.last().authorUser
Run Code Online (Sandbox Code Playgroud)