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: Rakesh
Author Info:

Rakesh is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

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