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
  • 10,791
  • 16
  • 72
  • 101

5 Answers5

23
list = list.collect { it.trim() }
sepp2k
  • 353,842
  • 52
  • 662
  • 667
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,779
  • 1
  • 39
  • 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
  • 156,222
  • 34
  • 208
  • 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,445
  • 18
  • 9
0

@sepp2k i think that works in ruby

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

luckykrrish
  • 128
  • 6