Java String join() function is used to join multiple strings to create a new string with the specified delimiter.
Java String join()
Java String join() method is added in Java 8 release. There are two variants of join() method, both of them are static methods.
1 2 3 4 5 |
public static String join(CharSequence delimiter, CharSequence... elements) public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) |
The first argument is the delimiter string to use when joining the strings. CharSequence
is an interface and some well known implementations are String, StringBuffer and StringBuilder.
Let’s look at these methods with some example.
1 2 3 4 |
String msg1 = String.join(",", "A", "B", new StringBuilder("C"), new StringBuffer("D")); System.out.println(msg1); |
Output: A,B,C,D
Notice that I have used StringBuffer and StringBuilder as elements to join since they implement CharSequence
interface.
Let’s look at an example where we will pass an Iterable whose elements will be joined with the given delimiter.
1 2 3 4 5 |
List<String> words = Arrays.asList(new String[] { "Hello", "World", "2019" }); String msg = String.join(" ", words); System.out.println(msg); |
Output: Hello World 2019
We can execute above code snippets using jshell terminal too.
Java String join() Example – jshell
Reference: API Doc