如何在 Grails 中不迭代地替换 Arraylist 中的字符串?

How to replace a String from Arraylist without iteration In Grails?

我想在不使用任何循环的情况下替换字符串中的一些单词。

 def tagList= []
 def tags= []
 tags.each { tag ->
   def newString = tag.replaceAll("sample", "")
   tagList.add(newString)
 }

这是 groovy 的优点,您可以直接替换字符串而无需迭代列表。

请尝试以下代码

 def tagList= []
 tagList = tags.join(',').replaceAll('sample','').split(',')

不迭代列表就很难修改它(我假设,这个需求只是措辞不当)。 each 通常用于副作用。如果要转换列表,请使用 collect.

如果您只对每个元素进行一次运算,您可以使用展开运算符代替:

def tagList = tags*.replaceAll('sample', '')