Java String.join() Method
December 08, 2022
On this page, we will learn using String.join()
method in our Java application.
Find the Java doc of
String.join()
method.
static String join(CharSequence delimiter, CharSequence... elements) static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)
Parameters:
The delimiter as
CharSequence
is the delimiter that separates each element.
The elements as
CharSequence
or Iterable
, are the elements to join together.
Returns:
A new string of elements separated by the delimeter.
Throws:
NullPointerException
: If delimiter or elements is null.
Examples using Elements as CharSequence
1.String result = String.join("-", "My", "country", "name", "is", "India"); System.out.println(result);
My-country-name-is-India
String result = String.join(",", "Ram", "Shyam", "Krishn", "Mohan"); System.out.println(result);
Ram,Shyam,Krishn,Mohan
String date = String.join("-", "15", "10", "1998"); String time = String.join(":", "10", "35", "45"); System.out.println(date + " "+ time);
15-10-1998 10:35:45
Examples using Elements as Iterable
We can use elements asIterable
containing the element of CharSequence
type. Iterable elements are List
, Set
and Queue
and they should contain String
, StringBuffer
, StringBuilder
etc.
Find the examples to join the elements.
1.
List<String> list = Arrays.asList("One", "Two", "Three", "Four"); String s = String.join("+", list); System.out.println(s);
One+Two+Three+Four
Set<String> set = new HashSet<>(); set.add("India"); set.add("UP"); set.add("Varanasi"); String s = String.join("-", set); System.out.println(s);
Varanasi-UP-India
ArrayBlockingQueue<String> abq = new ArrayBlockingQueue<String>(3); abq.put("Krishn"); abq.put("Suresh"); abq.put("Mahesh"); String s = String.join("|", abq); System.out.println(s);
Krishn|Suresh|Mahesh