Best way to concatenate List of String objects? [duplicate]
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);
Using Java 8+
String str = list.stream().collect(Collectors.joining())
or even
String str = String.join("", list);
Your approach is dependent on Java's ArrayList#toString() implementation.
While the implementation is documented in the Java API and very unlikely to change, there's a chance it could. It's far more reliable to implement this yourself (loops, StringBuilders, recursion whatever you like better).
Sure this approach may seem "neater" or more "too sweet" or "money" but it is, in my opinion, a worse approach.
A variation on codefin's answer
public static String concatStringsWSep(Iterable<String> strings, String separator) {
StringBuilder sb = new StringBuilder();
String sep = "";
for(String s: strings) {
sb.append(sep).append(s);
sep = separator;
}
return sb.toString();
}
If you are developing for Android, there is TextUtils.join
provided by the SDK.