Why StringJoiner when we already have StringBuilder?

Hitesh Garg picture Hitesh Garg · Dec 17, 2014 · Viewed 41.6k times · Source

I recently encountered with a Java 8 class StringJoiner which adds the String using the delimiters and adds prefix and suffix to it, but I can't understand the need of this class as it also uses StringBuilder at the backend and also performs very simple operation of appending the Strings.

Am I missing something by not actually understanding the real purpose of this class?

Answer

Martin Seeler picture Martin Seeler · Dec 17, 2014

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 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.