I need trim all elements in a list in groovy or grails? what is the best solution
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()
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()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With