Understanding Java's StringJoiner Implementation and Usage
This article explains why the original StringBuilder is limited, demonstrates how to use StringJoiner for comma‑separated strings, and provides a detailed analysis of the JDK source code including member fields, constructors, element addition, toString, length, merge, and empty‑value handling.
The original StringBuilder is rigid because it does not support automatic delimiters; to produce a comma‑separated string you must manually append commas after each element.
Using StringJoiner simplifies this task. Example code shows creating a StringJoiner with a comma delimiter and adding numbers via an IntStream :
StringJoiner sj = new StringJoiner(",");
IntStream.range(1,10).forEach(i -> sj.add(i+""));The JDK implementation of StringJoiner is built on top of StringBuilder . Key member variables are prefix , delimiter , suffix , value (a StringBuilder ), and emptyValue . The constructor copies the provided prefix, delimiter, and suffix, and pre‑computes emptyValue as prefix + suffix .
When adding an element, add(CharSequence newElement) calls prepareBuilder() . If a value already exists, the delimiter is appended first; otherwise the prefix is added and a new StringBuilder is created. The new element is then appended.
The toString() method returns emptyValue when no elements have been added; otherwise it appends the suffix only when needed, preserving the original value length to avoid side effects.
The length() method returns the length of the current content plus the suffix length, or the length of emptyValue when empty.
The merge(StringJoiner other) method appends another joiner’s content (excluding its prefix) to the current one, taking care to lock the length to avoid interference when merging the same instance.
Finally, setEmptyValue(CharSequence emptyValue) allows customizing the value returned when the joiner is empty, using Objects.requireNonNull for validation.
Overall, the design keeps prefix and delimiter handling inside the builder, defers suffix addition to toString() , and provides a flexible merge operation, making StringJoiner a convenient utility for building delimited strings.
Architect's Tech Stack
Java backend, microservices, distributed systems, containerized programming, and more.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.