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:
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:
Read More:
https://docs.oracle.com/javase/8/docs/api/java/util/StringJoiner.html
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!