Best way to concatenate List of String objects?

Jagmal picture Jagmal · Feb 7, 2009 · Viewed 238.8k times · Source

What is the best way to concatenate a list of String objects? I am thinking of doing this way:

List<String> sList = new ArrayList<String>();

// add elements

if (sList != null)
{
    String listString = sList.toString();
    listString = listString.subString(1, listString.length() - 1);
}

I somehow found this to be neater than using the StringBuilder/StringBuffer approach.

Any thoughts/comments?

Answer

Jeff Olson picture Jeff Olson · Feb 8, 2009

Use one of the the StringUtils.join methods in Apache Commons Lang.

import org.apache.commons.lang3.StringUtils;

String result = StringUtils.join(list, ", ");

If you are fortunate enough to be using Java 8, then it's even easier...just use String.join

String result = String.join(", ", list);