Possible Duplicate:
Clearest way to comma-delimit a list (Java)?
I have a List<String> and I need to convert this list into the single line and insert delimiters between String elements of this List, except position before first element and after last element;
I have made a cycle like this:
StringBuffer sb = new StringBuffer();
for (String str : list) {
sb.append(str).append(';');
}
if(sb.length() > 0)
sb.deleteCharAt(sb.length() - 1);
I don’t like delete last token sentence.
So, Which is more elegant way to do same?
Don’t re-invent the wheel… the apache commons-lang library has the
StringUtils.join()method, which does exactly what you want:Java 8 update:
In java 8, the
Stringclass has thejoin()method that does what you want: