Java is addressing issue of boilerplate code which developers can hardly avoid. One such boilerplate code is concatenating list of strings with a delimiter. This has been mainly used by developers to write formatted output.
For example:
For a list of city names we may want to print as
[Bangalore, Delhi, Mumbai, Chennai, Kolkata]
Traditional Way
| |
Output:
[Bangalore,Delhi,Mumbai,Chennai,Kolkata]
With StringJoiner API
With Java 8 we have java.util.StringJoiner.StringJoiner API. This does the same functionality as above but being less verbose.
| |
Output:
[Bangalore,Delhi,Mumbai,Chennai,Kolkata]

StringJoiner API needs three main inputs:
- delimiter
- prefix of the list (optional)
- suffix of the list (optional)
as indicated by its constructor:
java.util.StringJoiner.StringJoiner(CharSequence **delimiter**, CharSequence **prefix**, CharSequence **suffix**)
StringJoiner API can be used in various contexts where list of strings needs to be concatenated.
Following examples show few of them.
- Joining an array of strings
Class String has join() API to perform joining operation on given CharSequence or Iterable.
| |
Output:
Bangalore,Delhi,Mumbai,Chennai,Kolkata
- Joining strings coming from stream
| |
Output:
[Bangalore,Delhi,Mumbai,Chennai,Kolkata]
- Setting empty list string message
An empty list message can be set to be shown when joiner is empty.
| |
Output:
EMPTY!
- Merge of joiners
Given string joiner is added to the next element of the current string joiner.
| |
Output:
[A,B,C] {1|2|3} [A,B,C,1|2|3]
That’s it !