StringJoiner (Java Platform SE 8 ) (original) (raw)

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, itssj.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 "{", thesuffix is "}" and nothing has been added to theStringJoiner.
API Note:
The String "[George:Sally:Fred]" may be constructed as follows:
StringJoiner sj = new StringJoiner(":", "[", "]"); sj.add("George").add("Sally").add("Fred"); String desiredString = sj.toString();
A StringJoiner may be employed to create formatted output from aStream usingCollectors.joining(CharSequence). For example:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4); String commaSeparatedNumbers = numbers.stream() .map(i -> i.toString()) .collect(Collectors.joining(", "));
Since:
1.8
See Also:
Collectors.joining(CharSequence), Collectors.joining(CharSequence, CharSequence, CharSequence)

Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 1993, 2025, Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.