Java standard library provides StringJoiner class to highly efficient construct strings with a delimiter and optional prefix and suffix.

Java StringJoiner

As we know the Java StringBuilder is designed for highly efficient stitching of strings. But for some special cases, the StringJoiner class is the better option.

For example, we to construct a string in the following code:

public class Main {
    public static void main(String[] args) {

        String[] names = {"Bob", "Alice", "Grace"};
        var sb = new StringBuilder();
        sb.append("Hey ");
        for (String name : names) {
            sb.append(name).append(", ");
        }
        //then we need to remove the last one ","
        sb.delete(sb.length() - 2, sb.length());
        sb.append(".");
        System.out.println(sb.toString());
    }
}

Although, without any problems in the above code. But, for the cases like that to construct a string with a delimiter and optional prefix and suffix, the StringJoiner is the better option.

Let’s replace StringBuilder with StringJoiner, like the following code, it’s more convenient.

public class Main {
    public static void main(String[] args) {
        String[] ns = {"Bob", "Alice", "Grace"};
        var sj = new StringJoiner(", ", "Hey ", ".");
        for (String name: ns) {
            sj.add(name);
        }
        System.out.println(sj.toString());
    }
}

One thing you should know, in the internal of StringJoiner, it actually uses StringBuilder, so the efficiency is the same with StringBuilder. You can read the source code of StringJoiner to learn more.

Java String.join()

In fact, the static method join() of String is using Java StringJoiner internally to construct strings.

So, when no need to assign prefix and suffix, it’s more convenient to use String.join().

For example:

String message = String.join("-", "Java", "is", "cool");
// message returned is: "Java-is-cool"
//Note that if an element is null, then "null" is added.