Clean • Professional
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.
StringJoinerStringJoiner allows you to join strings with a delimiter, and optionally, a prefix and suffix.
StringJoiner joiner = new StringJoiner(delimiter);
delimiter → String inserted between each element.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.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 collectionExample – 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:
StringJoiner if prefix/suffix is not needed.StringJoiner and String.join() require Java 8 or later.StringJoiner when you need prefix and suffix in the final string.String.join() for simple concatenation of array or list elements.