Join multiple strings in Java using a delimiter
This post will discuss how to join multiple strings in Java (specified as an array, Iterable, varargs, etc.) with a delimiter.
1. Using Loop
The idea is to loop through the collection and append each element to a string separated by a delimiter. The variable prefix is used to avoid adding a delimiter at the end of the output.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import java.util.Arrays; import java.util.List; // Program to join multiple strings in Java using a delimiter class Main { public static void main(String[] args) { List<String> alphabets = Arrays.asList("A", "B", "C", "D"); String delimiter = ","; String result = "", prefix = ""; for (String s: alphabets) { result += prefix + s; prefix = delimiter; } System.out.println(result); } } |
Output:
A,B,C,D
2. Using Java 8 String.join() method
From Java 8 onward, we can use the String.join() method, which joins strings together with a specified separator. This method only works on Iterable and varargs.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import java.util.Arrays; import java.util.List; // Program to join multiple strings in Java 8 and above using a delimiter class Main { public static void main(String[] args) { List<String> alphabets = Arrays.asList("A", "B", "C", "D"); String delimiter = ","; String result = String.join(delimiter, alphabets); System.out.println(result); } } |
Output:
A,B,C,D
3. Using Guava’s Joiner Class
Like the String.join() method, Guava provides Joiner class, which joins elements of a collection (say, iterable, iterator, or Object[]) with a separator.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import com.google.common.base.Joiner; import java.util.Arrays; import java.util.List; // Program to join multiple strings using a delimiter with Guava class Main { public static void main(String[] args) { List<String> alphabets = Arrays.asList("A", "B", "C", "D"); String delimiter = ","; String result = Joiner.on(delimiter) .useForNull("null") .join(alphabets); System.out.println(result); } } |
Output:
A,B,C,D
That’s all about joining multiple strings in Java using a delimiter.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)