Hey, i try to trim each string item of an list in groovy
list.each() { it = it.trim(); }
But this only works within the closure, in the list the strings are still " foo", "bar " and " groovy ".
How can i achieve that?
Hey, i try to trim each string item of an list in groovy
list.each() { it = it.trim(); }
But this only works within the closure, in the list the strings are still " foo", "bar " and " groovy ".
How can i achieve that?
According to the Groovy Quick Start, using collect
will collect the values returned from the closure.
Here's a little example using the Groovy Shell:
groovy:000> ["a ", " b"].collect { it.trim() }
===> [a, b]
@sepp2k i think that works in ruby
and this works in groovy list = list.collect() { it.trim(); }
You could also use the spread operator:
def list = [" foo", "bar ", " groovy "]
list = list*.trim()
assert "foo" == list[0]
assert "bar" == list[1]
assert "groovy" == list[2]
If you really had to modify the list in place, you could use list.eachWithIndex { item, idx -> list[idx] = item.trim() }.
collect() is way better.