Java StringJoiner
Java added a new final class StringJoiner in [Link] package. It is used to construct a sequence of characters
separated by a delimiter. Now, you can create string by passing delimiters like comma(,), hyphen(-) etc. You
can also pass prefix and suffix to the char sequence.
StringJoiner Constructors
Constructor Description
Public StringJoiner(CharSequence It constructs a StringJoiner with no characters in it,
delimiter) with no prefix or suffix, and a copy of the supplied
delimiter. It throws NullPointerException if delimiter is
null.
Public StringJoiner(CharSequence It constructs a StringJoiner with no characters in it
delimiter,CharSequence using copies of the supplied prefix, delimiter and
prefix,CharSequence suffix) suffix. It throws NullPointerException if prefix,
delimiter, or suffix is null.
StringJoiner Methods
Method Description
Public StringJoiner add(CharSequence It adds a copy of the given CharSequence value as the
newElement) next element of the StringJoiner value. If newElement is
null,"null" is added.
Public StringJoiner merge(StringJoiner It adds the contents of the given StringJoiner without
other) prefix and suffix as the next element if it is non-empty.
If the given StringJoiner is empty, the call has no effect.
Public int length() It returns the length of the String representation of this
StringJoiner.
Public StringJoiner It sets the sequence of characters to be used when
setEmptyValue(CharSequence determining the string representation of this
emptyValue) StringJoiner and no elements have been added yet,
that is, when it is empty.
Java StringJoiner Example
1. // importing StringJoiner class
2. import [Link];
3. public class StringJoinerExample {
4. public static void main(String[] args) {
5. StringJoiner joinNames = new StringJoiner(","); // passing comma(,) as delimiter
6.
7. // Adding values to StringJoiner
8. [Link]("Rahul");
9. [Link]("Raju");
10. [Link]("Peter");
11. [Link]("Raheem");
12.
13. [Link](joinNames);
14. }
15. }
Output:
Rahul,Raju,Peter,Raheem