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?
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);