StringJoiner is a class in java.util package, which is used to construct a sequence of characters (strings) separated by separators, and can choose to start with the provided prefix and end with the provided suffix. Although this can also be done with the help of the StringBuilder class to append a separator after each string, StringJoiner provides a simple way to do this without writing too much code.
Java 8 introduced the java.util.StringJoiner
class, which is used to construct a sequence of characters (or a string) separated by a delimiter. The delimiter is specified when the StringJoiner
object is created, and elements can be added to the sequence using the add
method. The StringJoiner
class provides methods to handle prefix and suffix, which means it is possible to add a prefix or suffix to the resulting string.
The StringJoiner
class is useful when we need to concatenate multiple strings with a delimiter in between, such as when constructing CSV files, SQL statements, or HTML tables. Before Java 8, the StringBuilder
or StringBuffer
classes were used to achieve this, but they required more code to handle the delimiter and prefix/suffix.
Here's an example of using StringJoiner
to create a CSV string:
StringJoiner sj = new StringJoiner(","); sj.add("John"); sj.add("Doe"); sj.add("30"); String csv = sj.toString();
The resulting csv
string would be "John,Doe,30"
. We can also specify a prefix and suffix like this:
StringJoiner sj = new StringJoiner(",", "{", "}"); sj.add("John"); sj.add("Doe"); sj.add("30"); String csv = sj.toString();
The resulting csv
string would be "{John,Doe,30}"
.
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.