In this article, we will discuss how to join all strings using delimiter specified in the String’s join() method
1. String’s join() method:
- This String method joins all strings using specified delimiter
- and finally returns a composed string (or say concatenated string with delimiter)
- There are 2 variants or overloaded join() methods
- Both methods if the elements specified is null, then null is added
- Note: this is newly introduced in Java 1.8 version
1.1 Method Signature:
public static String join(CharSequence delimiter, CharSequence... elements);
public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements);
1.2 Parameters:
- delimiter –> this is used to separate each elements (each strings)
- elements –> elements which will be joined together using delimiter
1.3 Returns:
join() method | Returns |
join(CharSequence delimiter, CharSequence… elements); | Returns all elements joined together with delimiter in between all strings (i.e.; new composed string) |
join(CharSequence delimiter, Iterable<? extends CharSequence> elements); | Returns all elements present in collection object joined together with delimiter in between (i.e.; new composed string from List or Set) |
1.4 Throws:
- String’s join() method throws NullPointerException, if delimiter is NULL
2. Examples on String.join() method:
- To join all String elements with specified delimiter
- To join all String elements present inside Collection classes with specified delimiter
- To join all String elements when null is present as one such element
- To join all String elements when delimiter is null
2.1 To join all String elements with specified delimiter
- Here, all Strings that need to be joined or composed or concatenated are passed/supplied as arguments to join() method
- whereas, in the next example-2, all Strings that need to be joined are added to list/set first and then this collection object is passed/supplied as arguments to join() method
Method Signature:
public static String join(CharSequence delimiter, CharSequence... elements);
StringJoinMethodForVarargs.java
package in.bench.resources.string.methods;
public class StringJoinMethodForVarargs {
public static void main(String[] args) {
// Example-1 : message returned is:
// "BenchResources.Net-is-a-Java-weblog"
// hyphen (-) is a delimiter
String strDescForMessage = String.join("-",
"BenchResources.Net", "is", "a",
"Java", "weblog");
// print to console
System.out.println("The returned string message is : "
+ strDescForMessage);
// Example-2 : message returned is:
// "www.BenchResources.Net"
// dot or period (.) is a delimiter
String strDescForWebUrl = String.join(".", "www",
"BenchResources", "Net");
// print to console
System.out.println("The returned string web url is : "
+ strDescForWebUrl);
// Example-3 : message returned is:
// "30/07/2014"
// forward slash (/) is a delimiter
String strDescForDate = String.join("/",
"30", "07", "2014");
// print to console
System.out.println("The returned string date is : "
+ strDescForDate);
}
}
Output:
The returned string message is : BenchResources.Net-is-a-Java-weblog
The returned string web url is : www.BenchResources.Net
The returned string date is : 30/07/2014
2.2 To join all String elements present inside Collection classes with specified delimiter
- Here, all String values are added to List/Set Collection
- finally this Collection object is passed/supplied to join() method as arguments
Method Signature:
public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements);
StringJoinMethodForCollection.java
package in.bench.resources.string.methods;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
public class StringJoinMethodForCollection {
public static void main(String[] args) {
// create ArrayList for adding string elements
List<String> strList = new ArrayList<>();
// add elements to List
strList.add("BenchResources.Net");
strList.add("is");
strList.add("a");
strList.add("Java");
strList.add("weblog");
// Example-1 : message returned is:
// "BenchResources.Net-is-a-Java-weblog"
// converting List to String using hyphen (-)
String strMessage = String.join(" ", strList);
// print to console
System.out.println("The returned string message is : "
+ strMessage);
// create LinkedHashSet for adding string elements
Set<String> strSet = new LinkedHashSet<String>();
// add elements to Set
strSet.add("www");
strSet.add("BenchResources");
strSet.add("Net");
// Example-2 : message returned is:
// "www.BenchResources.Net"
// converting Set to String using dot/period (.)
String strWebUrl = String.join(".", strSet);
// print to console
System.out.println("The returned string web url is : "
+ strWebUrl);
}
}
Output:
The returned string message is : BenchResources.Net is a Java weblog
The returned string web url is : www.BenchResources.Net
2.3 To join all String elements when null is present as one such element
StringJoinMethodForNull.java
package in.bench.resources.string.methods;
public class StringJoinMethodForNull {
public static void main(String[] args) {
// Example-1 : message returned is:
// "Java-has-null-element"
// hyphen (-) is a delimiter
String strDescForMessage = String.join("-",
"Java", "has", null, "element");
// print to console
System.out.println("The returned string message "
+ "with NULL is : " + strDescForMessage);
}
}
Output:
The returned string message with NULL is : Java-has-null-element
2.4 To join all String elements when delimiter is null
StringJoinMethodForNullDelimiter.java
package in.bench.resources.override.tostring;
public class StringJoinMethodForNullDelimiter {
public static void main(String[] args) {
// Example-1 : NPE thrown
// null as delimiter
String strDescForMessage = String.join(null,
"test", "this", "string");
// print to console
System.out.println("The returned string message "
+ "with NULL is : " + strDescForMessage);
}
}
Output:
Exception in thread "main" java.lang.NullPointerException
at java.util.Objects.requireNonNull(Unknown Source)
at java.lang.String.join(Unknown Source)
at in.bench.resources.override.tostring
.StringJoinMethodForNullDelimiter
.main(StringJoinMethodForNullDelimiter.java:9)
Related Articles:
- Java – String charAt(int index) method
- Java – String compareTo(String anotherString) method
- Java – String compareToIgnoreCase(String str) method
- Java – String concat(String str) method
- Java – String contains(CharSequence s) method
- Java – String contentEquals(StringBuffer sb) method
- Java – String copyValueOf(char[] data) method (2)
- Java – String endsWith(String suffix) method
- Java – String equals(Object anObject) method
- Java – String equalsIgnoreCase(Object anObject) method
- Java – String format(String format, Object… args) method
- Java – String getBytes() method (4)
- Java – String getChars() method
- Java – String hashCode() method
- Java – String indexOf() method (4)
- Java – String intern() method
- Java – String isEmpty() method
- Java – String join() method (2)
- Java – String lastIndexOf() method (4)
- Java – String length() method
- Java – String matches(String regex) method
- Java – String regionMatches() method (2)
- Java – String replace(char oldChar, char newChar) method
- Java – String replace(CharSequence target, CharSequence replacement) method
- Java – String replaceAll(String regex, String replacement) method
- Java – String replaceFirst(String regex, String replacement) method
- Java – String split(String regex) method
- Java – String split(String regex, int limit) method
- Java – String startsWith(String prefix) method
- Java – String startsWith(String prefix, int toffset) method
- Java – String subSequence(int beginIndex, int endIndex) method
- Java – String substring(int beginIndex) method
- Java – String substring(int beginIndex, int endIndex) method
- Java – String toCharArray() method
- Java – String toLowerCase() method (2)
- Java – String toUpperCase() method (2)
- Java – String toString() method
- Java – String trim() method
- Java – String valueOf() method (9)
References:
- https://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html
- https://docs.oracle.com/javase/tutorial/essential/concurrency/imstrat.html
- https://docs.oracle.com/javase/tutorial/java/data/strings.html
- https://docs.oracle.com/javase/8/docs/api/java/lang/String.html
- https://docs.oracle.com/javase/8/docs/api/java/lang/class-use/String.html
- https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html
- https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html
Happy Coding !!
Happy Learning !!