Java StringJoiner & String.join()
Java provides convenient ways to combine multiple strings into a single string with delimiters, prefixes, or suffixes. Two common approaches are:
StringJoiner(introduced in Java 8)String.join()(also Java 8+)
These are useful when building comma-separated lists, CSV data, or formatted output.
1. Using StringJoiner
StringJoiner allows you to join strings with a delimiter, and optionally, a prefix and suffix.
Syntax
StringJoiner joiner = new StringJoiner(delimiter);
delimiter→ String inserted between each element.- Optional:
StringJoiner joiner = new StringJoiner(delimiter, prefix, suffix);
Example – Basic Usage
import java.util.StringJoiner;
public class StringJoinerExample {
public static void main(String[] args) {
StringJoiner joiner = new StringJoiner(", "); // Comma delimiter
joiner.add("Java");
joiner.add("Python");
joiner.add("C++");
System.out.println(joiner.toString());
}
}
Output:
Java, Python, C++
Example – With Prefix & Suffix
StringJoiner joiner = new StringJoiner(" | ", "[", "]");
joiner.add("Apple");
joiner.add("Banana");
joiner.add("Cherry");
System.out.println(joiner);
Output:
[Apple | Banana | Cherry]
Notes:
add()→ Adds elements.toString()→ Returns the combined string.- Prefix and suffix help format lists neatly.
2. Using String.join()
String.join() is a simpler alternative to join strings directly from arrays or collections.
Syntax
String joined = String.join(delimiter, elements...);
delimiter→ Separator between elementselements→ Strings, array, or collection
Example – Joining an Array of Strings
public class StringJoinExample {
public static void main(String[] args) {
String[] languages = {"Java", "Python", "C++"};
String result = String.join(", ", languages);
System.out.println(result);
}
}
Output:
Java, Python, C++
Example – Joining a List of Strings
import java.util.*;
public class StringJoinList {
public static void main(String[] args) {
List<String> fruits = Arrays.asList("Apple", "Banana", "Cherry");
String joined = String.join(" | ", fruits);
System.out.println(joined);
}
}
Output:
Apple | Banana | Cherry
Notes:
- Works for arrays, lists, or any iterable collection.
- Cleaner and shorter than
StringJoinerif prefix/suffix is not needed.
Points to Remember
- Both
StringJoinerandString.join()require Java 8 or later. - Use
StringJoinerwhen you need prefix and suffix in the final string. - Use
String.join()for simple concatenation of array or list elements. - Helps in creating CSV strings, HTML lists, or readable outputs.
