The examples on the StringJoiner Javadoc are very good at covering this. The whole point to to abstract away the choice of seperator from the act of adding entries. e.g. you can create a joiner, specify the seperator to use and pass it to a library to do the adding of elements or visa versa.
The String "[George:Sally:Fred]" may be constructed as follows:
StringJoiner is a kind of a Collector, although it doesn't implement the Collector interface. It just behaves as such. Besides you can pass delimiter, prefix and suffix, the StringJoiner may be employed to create formatted output from a Stream invoking Collectors.joining(CharSequence).
This is especially useful when working with parallel streams, because at some point the batches that are being process in parallel will need to be joined and this is where the StringJoiner takes place.
List<String> list = // ...;
// with StringBuilder
StringBuilder builder = new StringBuilder();
builder.append("[");
if (!list.isEmpty()) {
builder.append(list.get(0));
for (int i = 1, n = list.size(); i < n; i++) {
builder.append(",").append(list.get(i));
}
}
builder.append("]");
// with StringJoiner
StringJoiner joiner = new StringJoiner(",", "[", "]");
for (String element : list) {
joiner.add(element);
}
EDIT 6 years later
As noted in the comments, there are now much simpler solutions like String.join(", ", strings), which were not available back then. But the use case is still the same.