StringJoiner class is introduced in Java 8. It is a part of the java.util
package. The main purpose of a StringJoiner is to create a sequence of characters separated by a specified delimiter. You can optionally specify prefix and suffix as well. In this tutorial, we will discuss the add()
method of StringJoiner class.
Example 1: Using a delimiter
import java.util.StringJoiner;
public class StringJoinerExample {
public static void main(String[] args) {
// Create a StringJoiner with a comma delimiter
StringJoiner sj = new StringJoiner(", ");
// Adding elements to the StringJoiner object
sj.add("apple");
sj.add("banana");
sj.add("Mango");
// Print the resulting string
// Output: apple, banana, Mango
System.out.println(sj.toString());
}
}
Example 2: Using a delimiter, prefix, and suffix
import java.util.StringJoiner;
public class StringJoinerExample {
public static void main(String[] args) {
// Create a StringJoiner with a comma delimiter, prefix, and suffix
StringJoiner sj = new StringJoiner(", ", "[", "]");
// Add elements
sj.add("apple");
sj.add("banana");
sj.add("Mango");
// Print the resulting string
// Output: [apple, banana, Mango]
System.out.println(sj.toString());
}
}
Explanation
StringJoiner(CharSequence delimiter)
: It creates an emptyStringJoiner
instance with no elements in it, any element added to it, is separated by the specified delimiter. In Example 1, the delimiter is comma, so all the elements are separated by comma.StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix)
: Although prefix and suffix are optional, you can still specify them if needed. This is demonstrated in the Example 2.add(CharSequence newElement)
: It adds the specified character sequence (string) to the StringJoiner instance.
Leave a Reply