✅ What is StringJoiner
?
StringJoiner
is a class in java.util
that allows you to construct a sequence of characters separated by a delimiter, optionally with a prefix and suffix.
Think of it like a flexible alternative to StringBuilder
when you’re building things like CSV rows, human-readable lists, or HTML attributes.
📦 Package:
import java.util.StringJoiner;
🧠 Basic Syntax:
StringJoiner joiner = new StringJoiner(", ");
joiner.add("Java");
joiner.add("Python");
joiner.add("C++");
System.out.println(joiner.toString()); // Output: Java, Python, C++
✅ Constructor Options
1. Delimiter only
new StringJoiner(", ");
2. Delimiter, prefix, and suffix
new StringJoiner(", ", "[", "]");
StringJoiner j = new StringJoiner(", ", "[", "]");
j.add("red").add("green").add("blue");
System.out.println(j); // Output: [red, green, blue]
💡 Methods
Method | Description |
---|---|
.add(CharSequence element) | Adds a new element to the joiner |
.toString() | Returns the final joined string |
.merge(StringJoiner other) | Appends all elements from another joiner (ignores prefix/suffix of the other) |
.setEmptyValue(String emptyValue) | Sets the string to return when no elements have been added yet |
🧠 Example with .setEmptyValue()
StringJoiner sj = new StringJoiner(", ");
sj.setEmptyValue("Nothing to join");
System.out.println(sj); // Output: Nothing to join
🔁 Example with .merge()
StringJoiner j1 = new StringJoiner(", ");
j1.add("apple").add("banana");
StringJoiner j2 = new StringJoiner(", ");
j2.add("cherry").add("date");
j1.merge(j2);
System.out.println(j1); // Output: apple, banana, cherry, date
✅ When to Use StringJoiner
- When building CSV strings
- When formatting output with custom prefixes/suffixes
- When combining strings in a loop
- Under the hood, it’s used by
Collectors.joining()
in the Stream API
List<String> names = List.of("Alice", "Bob", "Carol");
String result = names.stream().collect(Collectors.joining(", ", "[", "]"));
System.out.println(result); // Output: [Alice, Bob, Carol]
🔚 Summary
Feature | StringJoiner |
---|---|
📌 Introduced in | Java 8 |
🔧 Used for | Building delimited strings with optional prefix/suffix |
🧠 Advantages | Clean, flexible, efficient for joining strings |
📚 Alternatives | StringBuilder , Collectors.joining() |
📦 Internally:
Under the hood, StringJoiner
uses a StringBuilder
internally to store and concatenate characters.
public final class StringJoiner {
private final String prefix;
private final String delimiter;
private final String suffix;
private String emptyValue;
private StringBuilder value; // <--- THIS IS KEY
}
So it inherits the same memory efficiency benefits as StringBuilder
.