Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assign "it" in each iteration (groovy)

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?

like image 793
Christopher Klewes Avatar asked Sep 22 '09 09:09

Christopher Klewes


People also ask

What is ${} in groovy?

String interpolation. Any Groovy expression can be interpolated in all string literals, apart from single and triple-single-quoted strings. Interpolation is the act of replacing a placeholder in the string with its value upon evaluation of the string. The placeholder expressions are surrounded by ${} .

What does [:] mean in groovy?

[:] creates an empty Map. The colon is there to distinguish it from [] , which creates an empty List. This groovy code: def foo = [:]


2 Answers

list = list.collect { it.trim() }
like image 140
sepp2k Avatar answered Sep 19 '22 04:09

sepp2k


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]
like image 21
John Wagenleitner Avatar answered Sep 20 '22 04:09

John Wagenleitner