I recently came to know about a new feature of java 8 StringJoiner
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.
Simply put, it can be used for joining Strings making use of a delimiter, prefix, and suffix.
This is a final class comes under Object class. It has following methods:
int length()
Returns the length of the String representation of this StringJoiner.
StringJoiner merge(StringJoiner other)
Adds the contents of the given StringJoiner without prefix and suffix as the next element if it is non-empty.
How to use StringJoiner?
Happy Reading!
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.
Simply put, it can be used for joining Strings making use of a delimiter, prefix, and suffix.
This is a final class comes under Object class. It has following methods:
StringJoiner add(CharSequence newElement)
Adds a copy of the given CharSequence value as the next element of the StringJoiner value.
Adds a copy of the given CharSequence value as the next element of the StringJoiner value.
int length()
Returns the length of the String representation of this StringJoiner.
StringJoiner merge(StringJoiner other)
Adds the contents of the given StringJoiner without prefix and suffix as the next element if it is non-empty.
StringJoiner setEmptyValue(CharSequence emptyValue)
Sets the sequence of characters to be used when determining the string representation of this StringJoiner and no elements have been added yet, that is, when it is empty.
Sets the sequence of characters to be used when determining the string representation of this StringJoiner and no elements have been added yet, that is, when it is empty.
How to use StringJoiner?
- Join String by a delimiter
- Join String by a delimiter and starting with a supplied prefix and ending with a supplied suffix.
StringJoiner sj = new StringJoiner(","); sj.add("aaa"); sj.add("bbb"); sj.add("ccc"); String result = sj.toString(); //aaa,bbb,ccc
StringJoiner sj = new StringJoiner("/", "prefix-", "-suffix"); sj.add("2016"); sj.add("02"); sj.add("26"); String result = sj.toString(); //prefix-2016/02/26-suffix
Happy Reading!
Superb ... Nice blog..
ReplyDelete