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());
    }
}

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap