Why StringJoiner when we already have StringBuilder? Why StringJoiner when we already have StringBuilder? java java

Why StringJoiner when we already have StringBuilder?


StringJoiner is very useful, when you need to join Strings in a Stream.

As an example, if you have to following List of Strings:

final List<String> strings = Arrays.asList("Foo", "Bar", "Baz");

It is much more simpler to use

final String collectJoin = strings.stream().collect(Collectors.joining(", "));

as it would be with a StringBuilder:

final String collectBuilder =    strings.stream().collect(Collector.of(StringBuilder::new,        (stringBuilder, str) -> stringBuilder.append(str).append(", "),        StringBuilder::append,        StringBuilder::toString));

EDIT 6 years laterAs 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.


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 sj = new StringJoiner(":", "[", "]");sj.add("George").add("Sally").add("Fred");String desiredString = sj.toString();

A StringJoiner may be employed to create formatted output from a Stream using Collectors.joining(CharSequence). For example:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4);String commaSeparatedNumbers = numbers.stream()    .map(i -> i.toString())    .collect(Collectors.joining(", "));


It may simplify your code in some use cases:

List<String> list = // ...;// with StringBuilderStringBuilder 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 StringJoinerStringJoiner joiner = new StringJoiner(",", "[", "]");for (String element : list) {    joiner.add(element);}