StringJoiner Class in Java
StringJoiner is a class in java.util package is used to construct a sequence of characters(strings) separated by a delimiter and optionally starting with a supplied prefix and ending with a given suffix. Though this can also be done with the help of the StringBuilder class to append delimiter after each string, StringJoiner provides an easy way to do that without much code to write.
Constructors of StringJoiner Class
1. StringJoiner(CharSequence delimiter): It constructs a StringJoiner with no characters, no prefix or suffix, and a copy of the supplied delimiter.
public StringJoiner(CharSequence delimiter)
Parameters: The sequence of characters to be used between each element added to the StringJoiner value
Exception Thrown: NullPointerException if the delimiter is null
2. StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix): It constructs a StringJoiner with no characters using copies of the supplied prefix, delimiter, and suffix. If no characters are added to the StringJoiner and methods accessing the string value are invoked, it will return the prefix + suffix (or properties thereof) in the result unless setEmptyValue has first been called.
public StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix)
- The sequence of characters to be used between each element added to the StringJoiner value
- The sequence of characters to be used at the beginning
- The sequence of characters to be used at the end
Exception Thrown: NullPointerException if prefix, delimiter, or suffix is null.
Methods of StringJoiner Class
|add()||Adds a copy of the given CharSequence value as the next element of the StringJoiner value. If newElement is null, then “null” is added.|
|length()||Returns the length of the String representation of this StringJoiner.|
|merge()||Adds the contents of the given StringJoiner without prefix and suffix as the next element if it is non-empty. If the given StringJoiner is empty, the call has no effect. Suppose the other StringJoiner is using a different delimiter. In that case, elements from the other StringJoiner are concatenated with that delimiter, and the result is appended to this StringJoiner as a single element.|
|toString()||Returns the String object of this StringJoiner|
|setEmptyValue()||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|
sj1 is empty Ram,Shyam Length of sj1 : 9 Ram,Shyam,Alice:Bob Length of new sj1 : 19
This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.