Java StringJoiner Class With Examples


You can find the StringJoiner Class under java.util package. This class is really helpful if you want to generate a sequence of strings that is seperated by a delimiter.

Let's take a look at a few examples.


Example 1: StringJoiner with Comma Delimiter

package org.code2care.examples;

import java.util.StringJoiner;

public class StringJoinerExample1 {

    public static void main(String[] args) {

        String delimiter = ",";
        StringJoiner stringJoiner = new StringJoiner(delimiter);
        stringJoiner.add("EMPID: 101");
        stringJoiner.add("Name: Sam");
        stringJoiner.add("Age: 23");

        System.out.println(stringJoiner.toString());

    }
}
Output:

EMPID: 101,Name: Sam,Age: 23



Example 2: Adding a Prefix and Suffix

We can also add a prefix or a suffix to the StringJoiner object by passing them to the constructor.

String delimiter = ",";
StringJoiner stringJoiner = new StringJoiner(delimiter,"\"","\"");
stringJoiner.add("EMPID: 101");
stringJoiner.add("Name: Sam");
stringJoiner.add("Age: 23");
Output:

"EMPID: 101,Name: Sam,Age: 23"


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