11

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?

Christopher Klewes
  • 11,181
  • 18
  • 74
  • 102

5 Answers5

23
list = list.collect { it.trim() }
sepp2k
  • 363,768
  • 54
  • 674
  • 675
6

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]
John Wagenleitner
  • 10,967
  • 1
  • 40
  • 39
2

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]
coobird
  • 159,216
  • 35
  • 211
  • 226
1

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.

John Stoneham
  • 2,485
  • 19
  • 10
0

@sepp2k i think that works in ruby

and this works in groovy list = list.collect() { it.trim(); }

luckykrrish
  • 128
  • 6