groovy: change each element of a list and join

Tag: collections , groovy , closures Author: wsp52539 Date: 2012-12-03

I want to wrap each element of a list in single-quotes and join them into a string.

Sample input: ["aa", "bb", "cc"]

Expected output: "'aa', 'bb', 'cc'"

I guessed that this could be done with a collect+closure, so I tried:

def mylist = ["aa", "bb", "cc"]
println mylist.collect{ 'it' }.join(', ')

But the output is: "it, it, it" and this is not what I want.

How can I append and pre-pend a single quote to each element of the list? Any other oneliner (or short) groovy solutions apart from collect and join?

Best Answer

You should try

mylist.collect{ "'$it'" }.join(', ')

with 'it' you just return the string "it".

comments:

it does not work...I tried mylist.collect{ "'$it.toUpperCase()'" }.join(', ')...not sure if that is due to toUpperCase method..
That's because you aren't calling the variable in the string the right way. Try this: mylist.collect{ "'${it.toUpperCase()}'" }.join(', ')

Other Answer1

You can try this

mylist.collect { "'" + it+ "'" }.join(',')