Module java.base
Package java.util

Class StringJoiner


public final class StringJoiner extends Object
StringJoiner is used to construct a sequence of characters separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix.

Prior to adding something to the StringJoiner, its sj.toString() method will, by default, return prefix + suffix. However, if the setEmptyValue method is called, the emptyValue supplied will be returned instead. This can be used, for example, when creating a string using set notation to indicate an empty set, i.e. "{}", where the prefix is "{", the suffix is "}" and nothing has been added to the StringJoiner.

API Note:

The String "[George:Sally:Fred]" may be constructed as follows:

 StringJoiner sj = new StringJoiner(":", "[", "]");
 String desiredString = sj.toString();

A StringJoiner may be employed to create formatted output from a Stream using Collectors.joining(CharSequence). For example:

 List<Integer> numbers = Arrays.asList(1, 2, 3, 4);
 String commaSeparatedNumbers =
     .map(i -> i.toString())
     .collect(Collectors.joining(", "));

See Also: