Leepoint Java Reference Notes on the Java language and its standard library.

Joining an array into a string

Almost always one line.

For an array of strings:

String[] words = {"alpha", "beta", "gamma"};
String joined = String.join(", ", words);      // "alpha, beta, gamma"

String.join takes a delimiter and either a varargs list or any Iterable, so it works on a List unchanged.

For other types

String.join needs strings. For anything else, a stream converts first:

int[] numbers = {1, 2, 3};
String s = Arrays.stream(numbers)
                 .mapToObj(String::valueOf)
                 .collect(Collectors.joining(", "));

For an object array:

String s = Arrays.stream(people)
                 .map(Person::name)
                 .collect(Collectors.joining("; "));

Collectors.joining also takes a prefix and suffix, which saves handling the brackets yourself:

.collect(Collectors.joining(", ", "[", "]"))

Just for debugging

If you only want to look at the contents, do not build anything:

System.out.println(Arrays.toString(numbers));     // [1, 2, 3]
System.out.println(Arrays.deepToString(grid));    // nested arrays

Printing the array itself gives [I@1b6d3586 — the type and a hash code — which is the first confusing output most people meet.

The manual version

Occasionally you need control over each element:

StringBuilder sb = new StringBuilder();
for (int i = 0; i < words.length; i++) {
    if (i > 0) sb.append(", ");
    sb.append(words[i]);
}
String joined = sb.toString();

The if (i > 0) handles the separator without a trailing one. The alternative — append the delimiter after every element and delete the last — works but is easy to get wrong on an empty array.

Not this

String joined = "";
for (String w : words) {
    joined += w + ", ";        // quadratic, and a trailing comma
}

Each += copies the whole string built so far. It is fine for five elements and a real problem for ten thousand.

Nulls in the array

String.join writes the four characters null for a null element rather than throwing. If that is not what you want, filter first:

String s = Arrays.stream(words)
                 .filter(Objects::nonNull)
                 .collect(Collectors.joining(", "));

StringJoiner

The class behind String.join, useful directly when you are appending in a loop and want the delimiter handled:

StringJoiner j = new StringJoiner(", ", "[", "]");
for (String w : words) {
    j.add(w);
}
String s = j.toString();     // [alpha, beta, gamma]

It also takes an “empty value” to use when nothing was added, which removes the usual special case for an empty collection.