![]() |
VOOZH | about |
Prior to Java 8 when we need to concatenate a group of strings we need to write that code manually in addition to this we needed to repeatedly use delimiter and sometimes it leads to several mistakes but after Java 8 we can concatenate the strings using StringJoiner class and String.join() method then we can easily achieve our goal.
Example: Without StringJoiner Class and without String.join() method
Approach :
DSA gfg FAANG gfg ALGO -------------------- DSA gfg FAANG gfg ALGO
StringJoiner is used to construct a sequence of characters separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix. In simple words in the constructor of StringJoiner calls we can pass Three parameters delimiter, suffix, prefix. Prefix be added to the start of a String and suffix will be at the end. For adding the strings we will need to simply call the add() method on the StringJoiner class.
Syntax :
If we have suffix and prefix
StringJoiner joined=StringJoiner(delimiter,prefix,suffix) joined.add(string1); joined.add(string2); joined.add(string3);
If we don't have suffix and prefix
StringJoiner joined=StringJoiner(delimiter) joined.add(string1); joined.add(string2); joined.add(string3);
Approach:
Program of joining Strings using StringJoiner class :
[DSA gfg FAANG gfg ALGO] -------------------- [DSA gfg FAANG gfg ALGO]
The java.lang.string.join() method concatenates the given element with the delimiter and returns the concatenated string. Note that if an element is null, then null is added. The join() method was introduced in java string since JDK 1.8. String.join() method takes two parameters first is a delimiter and the second can be a list or array of elements or elements separated by ,(comma).
Syntax :
In the case of individual elements
String joined=String.join("delimiter","element1","element2,"element3"...);
In the case of List
String joined2=String.join("delimiter",listObject);
Return Type: It returns the string joined by using of delimiter
Example:
Approach: Joining strings using String.join() method
DSA gfg FAANG gfg ALGO -------------------- DSA gfg FAANG gfg ALGO