StringJoiner in Java

StringJoiner is a class introduced in Java 8 that provides an easy and efficient way to concatenate a sequence of strings with a delimiter. It is a useful tool when working with lists of data, such as outputting comma-separated values or creating SQL statements with a list of parameters.

The StringJoiner class is located in the java.util package and can be used in two different ways: either by using its default constructor or by specifying a delimiter and optionally a prefix and suffix.

Using the Default Constructor

To use the default constructor, simply create a new instance of the StringJoiner class. This will create an empty StringJoiner object with a default delimiter of “,”:


StringJoiner sj = new StringJoiner(",");


You can then add strings to the StringJoiner object using the add method:


sj.add("apple");
sj.add("banana");
sj.add("orange");

This will add the strings “apple”, “banana”, and “orange” to the StringJoiner object, separated by commas. You can retrieve the resulting concatenated string by calling the toString method:


String result = sj.toString();
System.out.println(result); // Output: apple,banana,orange

Using the Delimiter, Prefix, and Suffix

If you want to specify a different delimiter or add a prefix or suffix to the concatenated string, you can use the constructor that takes these parameters:


StringJoiner sj = new StringJoiner(",", "{", "}");

This will create a StringJoiner object with a delimiter of “,”, a prefix of “{“, and a suffix of “}”. You can then add strings to the StringJoiner object and retrieve the concatenated string in the same way as before:


sj.add("apple");
sj.add("banana");
sj.add("orange");
String result = sj.toString();
System.out.println(result); // Output: {apple,banana,orange}

If the StringJoiner object has not had any strings added to it, calling toString will return only the prefix and suffix:


StringJoiner sj = new StringJoiner(",", "{", "}");
String result = sj.toString();
System.out.println(result); // Output: {}

Handling Empty Values

By default, if you try to add a null or empty string to a StringJoiner object, it will simply be ignored. However, you can specify a different string to use in these cases by calling the setEmptyValue method:


StringJoiner sj = new StringJoiner(",", "{", "}");
sj.setEmptyValue("No fruits added");
String result = sj.toString();
System.out.println(result); // Output: No fruits added

Now, if no strings are added to the StringJoiner object, the toString method will return the empty value that was specified.

Conclusion

StringJoiner provides a simple and efficient way to concatenate a sequence of strings with a delimiter. Its flexibility in allowing you to specify a prefix and suffix, as well as handle empty values, makes it a powerful tool when working with lists of data. By understanding how to use StringJoiner in Java, you can make your code more concise and readable.