What is StringJoiner in Java?

In Java, we can use StringJoiner to join strings with a separator. We can also choose to specify the prefix and suffix added to the result strings.

Syntax

StringJoiner(CharSequence delimiter)
StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix)

To use StringJoiner, create a StringJoinerobject and call the add method by passing the string to be joined.

Code

import java.util.StringJoiner;
class JoinString {
public static void main( String args[] ) {
StringJoiner joiner = new StringJoiner(", ");
joiner.add("I");
joiner.add("Love")
.add("Badminton");
System.out.println(joiner.toString());
}
}

In the code above, we:

  • Created a StringJoiner with , as the separator of the string.

  • Used the add() method to add some strings to the StringJoiner. This method returns the reference to the StringJoiner to chain the add() method.

  • Called the toString() method to convert the StringJoiner into a string. The resultant string is the joined version of all strings separated by the separator.

Example with prefix and suffix

import java.util.StringJoiner;
class JoinString {
public static void main( String args[] ) {
String SEPARATOR = "-";
String PREFIX = "{";
String SUFFIX = "}";
StringJoiner joiner;
joiner = new StringJoiner(SEPARATOR, PREFIX, SUFFIX);
joiner.add("I");
joiner.add("Love")
.add("Badminton");
System.out.println(joiner.toString());
}
}

In the code above, we created a StringJoiner named joiner with - as a separator, { as PREFIX, and } as SUFFIX.

The resulting string will start with {, end with }, and the separator - will be added between the strings.