Over a million developers have joined DZone.

Java 8 StringJoiner – Old Wine With a New Bottle

DZone's Guide to

Java 8 StringJoiner – Old Wine With a New Bottle

Java 8 introduces the StringJoiner class to help with everyone's favorite task: Joining strings together. Check out how to use it in this article!

Free Resource

Bitbucket is for the code that takes us to Mars, decodes the human genome, or drives your next car. What will your code do? Get started with Bitbucket today, it's free.


Ultimately Java 8 shipped with StringJoiner class under the java.util package. I don’t think it is a very different implementation to join the strings compared to our old school approach by using StringBuffer/StringBuilder. We will see the usage of the StringJoiner and the internal implementation of it.

For example, I have two strings as “Smart” and “Techie” and I want join those Strings as [Smart,Techie]. In this case, I have the prefix as “[” , the suffix as “]” and the delimiter as “,”.  StringJoiner has two constructors as given below.

StringJoiner(CharSequence delimiter)
StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix)

We want to have prefix and suffix, hence we will use the second constructor for our example.

StringJoiner sjr = new StringJoiner(",", "[", "]");
System.out.println("The final Joined string is " + sjr);

If we don’t want to have the prefix and suffix, then:

StringJoiner sjr1 = new StringJoiner(",");
System.out.println("The final Joined string is " + sjr1);

Now, we will see the implementation of add and toString() method.

public StringJoiner add(CharSequence newElement) {
   return this;

The prepareBuilder() implementation is given below.

private StringBuilder prepareBuilder() {
    if (value != null) {
    } else {
       value = new StringBuilder().append(prefix);
    return value;

From the above implementations it is evident that the StringJoiner follows an old school approach.

The toString() implementation is given below.

public String toString() {
    if (value == null) {
      return emptyValue;
    } else {
    if (suffix.equals("")) {
      return value.toString();
    } else {
    int initialLength = value.length();
    String result = value.append(suffix).toString();
    // reset value to pre-append initialLength
    return result;

Happy Learning!!!

Bitbucket is the Git solution for professional teams who code with a purpose, not just as a hobby. Get started today, it's free.

strings ,implementation ,approach ,example ,java ,join

Published at DZone with permission of Siva Prasad Rao Janapati, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}