![]() |
VOOZH | about |
StringJoiner class in Java provides an efficient way to concatenate multiple strings with a defined delimiter(character), optional prefix, and suffix. This class is especially useful when constructing formatted strings dynamically.
Example 1:
Joined String: geeks, for, geeks
Explanation: In the above example, we have created a StringJoiner object with a comma and space as the delimiter. The toString() method is used to make the addition of string with the specified delimiter.
Example 2: Here, we will use the StringJoinerto join elements of an array of Strings.
Geeks, for, Geeks
1. StringJoiner(CharSequence delimiter): It creates a StringJoiner with a specified delimiter.
Syntax:
public StringJoiner(CharSequence delimiter)
2. StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix): It creates a StringJoiner with a delimiter, prefix, and suffix.
Syntax:
public StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix)
| Method | Action Performed |
|---|---|
| add() | Adds a string to the StringJoiner. |
| length() | Returns the length of the joined string. |
| merge() | Merges the contents of another StringJoiner into the current one. |
| toString() | Returns the final joined string. |
| setEmptyValue() | Specifies a default value if no elements are added. |
StringJoiner with elements: geeks, for, geeks Empty StringJoiner: No elements to join StringJoiner with prefix and suffix: [geeks | for | geeks] Length of joined string: 17