Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert list to string in Groovy and remove brackets without using replace?

Tags:

string

groovy

So I have the following code where I add some elements to a list, sort them and print as a string..

 def officeWorkers = []
 officeWorkers << "Jim Halpert"
 officeWorkers << "Dwight Shrute"
 officeWorkers << "Toby Flenderson"
 officeWorkers.sort()
 println("I wish my co workers were ${officeWorkers.toString()}")

The resulting string has opening and closing brackets ('[', ']') which I don't want ("I wish my co workers were [Dwight Shrute, Jim Halpert, Toby Flenderson]").

It seems one way to remove those brackets is to use String's replace function as suggested here.

But what if in the actual list I am using there are already brackets in the values, they would get replaced also.

So is there a way to print out this list as a string without having those brackets show up and without using the replace function?

like image 555
AbuMariam Avatar asked Apr 05 '16 17:04

AbuMariam


1 Answers

Use join:

println("I wish my co workers were ${officeWorkers.join(', ')}")
like image 87
tim_yates Avatar answered Sep 19 '22 21:09

tim_yates