Java String.join() Method

By Arvind Rai, 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) 
Returns a new string composed of given elements delimited by given delimiter.
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); 
Output
My-country-name-is-India 
2.
String result = String.join(",", "Ram", "Shyam", "Krishn", "Mohan");
System.out.println(result); 
Output
Ram,Shyam,Krishn,Mohan 
3.
String date = String.join("-", "15", "10", "1998");
String time = String.join(":", "10", "35", "45");
System.out.println(date + " "+ time); 
Output
15-10-1998 10:35:45 

Examples using Elements as Iterable

We can use elements as Iterable 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); 
Output
One+Two+Three+Four 
2.
Set<String> set = new HashSet<>();
set.add("India");
set.add("UP");
set.add("Varanasi");
String s = String.join("-", set);
System.out.println(s); 
Output
Varanasi-UP-India 
3.
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); 
Output
Krishn|Suresh|Mahesh 

Reference

Class String
POSTED BY
ARVIND RAI
ARVIND RAI











©2023 concretepage.com | Privacy Policy | Contact Us