Last Updated: 13 September, 2023
In Java, StringJoiner is a final class introduced in Java 8 as part of the java.util package.
StringJoiner class is used to construct a sequence of characters (strings) separated by a delimiter like a comma (,), hyphen (-), etc. and optionally starting with a supplied prefix and ending with a given suffix.
The StringJoiner class provides a convenient way to build a sequence of strings separated by a delimiter.
StringJoiner Class Declaration:
1. public StringJoiner (CharSequence delimiter)
It constructs a StringJoiner with no characters in it, with no prefix or suffix, and a copy of the supplied delimiter.
Parameter:
delimiter - the sequence of characters to be used between each element added to the StringJoiner value
Throws:
It throws a NullPointerException if the delimiter is null.
2. public StringJoiner (CharSequence delimiter, CharSequence prefix, CharSequence suffix)
It constructs a StringJoiner with no characters in it using copies of the supplied prefix, delimiter and suffix.
Parameters:
Throws:
It throws a NullPointerException if the prefix, delimiter, or suffix is null.
Methods | Description |
public StringJoiner add (CharSequence newElement) | Adds a copy of the given CharSequence value as the next element of the StringJoiner value. If newElement is null, then “null” is added. |
public int length() | Returns the length of the String representation of this StringJoiner. |
public StringJoiner merge (StringJoiner other) | Adds the contents of the given StringJoiner without prefix and suffix as the next element if it is non-empty. |
public String toString() | Returns the String object of this StringJoiner. |
public StringJoiner setEmptyValue (CharSequence emptyValue) | Sets the string to be used when determining the string representation of this StringJoiner, and no elements have been added yet; that is when it is empty. |
Example 1: Java StringJoiner class example
Output
Apple,Mango,Orange,Grapes,Pear
Potato|Onion|Tomato|Pea|Brinjal
Example 2: Java StringJoiner class example
Output
(Apple,Mango,Orange,Grapes,Pear)
Example 3: Java StringJoiner class example
Output
Fruits: (Apple,Mango,Orange,Grapes,Pear)
Vegetables: prePotato-Onion-Tomato-Pea-Brinjalsuff
Fruits + Vegetables: (Apple,Mango,Orange,Grapes,Pear,Potato-Onion-Tomato-Pea-Brinjal)
Example 4: Java StringJoiner class example
Output
StringJoiner:
It is an empty.
Apple,Mango,Orange,Grapes,Pear
Length: 30
Apple,Mango,Orange,Grapes,Pear
Character at index 3: l
Apple,Mango,Orange,Grapes,Pear,Coconut
New Length: 38
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/StringJoiner.html
That's all guys, hope this Java article is helpful for you.
Happy Learning.
feedback@javabytechie.com