groovy: change each element of a list and join

15,647

You should try

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

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

Share:
15,647
nonbeing
Author by

nonbeing

Make software or break software, but automate ALL the things!

Updated on June 03, 2022

Comments

  • nonbeing
    nonbeing almost 2 years

    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?

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