Convert Groovy List To String

Groovy is now getting popular with the help of the increasing user base of Gradle. Groovy language is exceptional in being a very concise and powerful language. Compared to Java, writing things just needs very short code that is human friendly and makes developers happy. One common task we deal in most generic programming language is manipulating Strings and List. Below is an example on how to convert a Groovy List to String.

Solution without Groovy

Groovy is just the superset of the Java language. This means that whatever is a valid Java code is a valid Groovy code as Groovy just extends the Java language. This is cool if we are coming from the Java community as we can bring our experience and knowledge in Groovy. Specially in API. Assuming we have a list in Java and we want to convert it to String separated by comma, just using the toString() on the list object will do the trick.
myList.add("Apple");
myList.add("Banana");
myList.add("Carrots");
String stringRepresentationOfList = myList.toString();
System.out.println(stringRepresentationOfList);

The output would be our expected:

[Apple, Banana, Carrots]

But the hard part is if we want to convert a list to string using a custom separator. In this case, we need a longer code in Java to do the trick. Say for example, we use dash as separator.
String separator = "-";
List<String> myList = new ArrayList<String>();
myList.add("Apple");
myList.add("Banana");
myList.add("Carrots");
StringBuilder sb = new StringBuilder();
for (String item : myList) {
    if (sb.length() > 0) {
        sb.append(separator);
    }
    sb.append(item);
}
String stringRepresentationOfList = sb.toString();
System.out.println(stringRepresentationOfList);

This will give the output:

Apple-Banana-Carrots

Groovy solutionto to Convert a List to String

Since Groovy is a powerful and concise language, many things that are inherently hard in Java are quite easy and short in Groovy. If we want to convert a Groovy List to String, the code will just look something like below:

There is a nice trick in Groovy on how to convert a list to String:

def myList = ["Apple", "Banana", "Carrot"]
String stringRepresentationOfList = myList.join("-,")
println stringRepresentationOfList;

And this does the trick. Just a one liner and we were able to convert a List to String in Groovy using a custom separator. The output should be the same as above:

Apple-Banana-Carrots