Java 8 has introduced StringJoiner class which has helped a lot to all the developers dealing Strings and delimiters. It is used to construct a sequence of characters separated by a delimiter. Optionally a prefix can be added at start and suffix can be added at the end of String.
Constructs a StringJoiner with no characters in it, with no prefix or suffix, and a copy of the supplied delimiter.
StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix)
Constructs a StringJoiner with no characters in it using copies of the supplied prefix, delimiter and suffix.
StringJoiner setEmptyValue(CharSequence emptyValue)
StringJoiner add(CharSequence newElement)
StringJoiner merge(StringJoiner other)
Let’s look at the code sample for constructors and the methods of StringJoiner :
#1 . Join Strings with a delimiter
Output : Delimiter joined String: hello,world
#2. Join Strings with delimiter, prefix and suffix
Output: With delimiter, Prefix and Suffix: [Shalini,Goyal]
#3. merge() and length() methods
Hope you found the explanation and examples for StringJoiner useful. This feature of Java8 is really easy to implement.