Grails Cookbook - A collection of tutorials and examples

Groovy List To String

Often times we need to concatenate items of a list to form a String. For example, a comma separated String. There is a nice trick in Groovy on how to convert a Groovy List to String.

Long-cut Java way solution

If it is in Java, we can implement it like this

List<String> stringList = new ArrayList<String>();
stringList.add("A");
stringList.add("B");
stringList.add("C");
StringBuilder sb = new StringBuilder()
for (String item:stringList) {
    if (sb.length() > 0 ) {
      sb.append(", ");
    }
   sb.append(item)
}
String result = sb.toString()

The logic is that we loop each item and construct the String to a StringBuilder.

Groovy solution using join

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

def stringList = ["A", "B", "C"]
String result = stringList.join(",")

And it solves the problem quickly!

Other Groovy Tutorials