How to Clear StringJoiner in Java 8

If you are making use of the StringJoiner class from the java.util package and you want to clear the object for the elements it holds, there is no method available to do so, such as clear() or flush().

So, the efficient way to achieve this is by re-using the object reference and creating a new object of StringJoiner.

Let's take a look at an example:

package org.code2care.examples;

import java.util.StringJoiner;

public class StringJoinerClearExample {

    public static void main(String[] args) {
        StringJoiner stringJoiner = new StringJoiner(",");
        stringJoiner.add("1");
        stringJoiner.add("2");
        stringJoiner.add("3");
        stringJoiner.add("4");
        System.out.println(stringJoiner.toString());

        //Clearing StringJoiner Object
        stringJoiner = new StringJoiner(",");
        System.out.println(stringJoiner.toString());
    }
}

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!