Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I trim all elements in a list using Groovy?

Tags:

grails

groovy

I need trim all elements in a list in groovy or grails? what is the best solution

like image 260
user1497563 Avatar asked Jul 06 '12 05:07

user1497563


2 Answers

Assuming it is a list of strings and you want to trim each string, you can do it using the spread operator (*.)

list = [" abc ", " xyz "]
list*.trim()
like image 166
gkamal Avatar answered Oct 10 '22 17:10

gkamal


You can use the collect method or the spread operator to create a new list with the trimmed elements:

def strs = ['a', ' b', ' ']
assert strs.collect { it.trim() } == ['a', 'b', '']
assert strs*.trim() == ['a', 'b', '']

In those cases, the original list isn't modified. If you want to trim the strings in place, you'll need to iterate through the list with an index:

for (i in 0..<strs.size()) {
    strs[i] = strs[i].trim()
}
like image 20
ataylor Avatar answered Oct 10 '22 16:10

ataylor