Collectors.joining()
A collector that joins the strings of a stream into one.
Available since: Java 8
Syntax
static Collector<CharSequence, ?, String> joining()
static Collector<CharSequence, ?, String> joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix)Parameters
| Parameter | Type | Description |
|---|---|---|
| delimiter | CharSequence | Optional delimiter. |
| prefix | CharSequence | Optional string at the start. |
| suffix | CharSequence | Optional string at the end. |
Return value
Collector<CharSequence, ?, String>A collector into a single string.
Examples
A delimiter, a prefix and a suffix:
void main() {
List<String> tags = List.of("java", "streams", "api");
IO.println(tags.stream().collect(Collectors.joining()));
IO.println(tags.stream().collect(Collectors.joining(", ")));
IO.println(tags.stream().collect(Collectors.joining(" | ", "[", "]")));
}Output:
javastreamsapi
java, streams, api
[java | streams | api]Numbers must be turned into strings first:
void main() {
String csv = Stream.of(3, 1, 4).map(String::valueOf).collect(Collectors.joining(","));
IO.println(csv);
}Output:
3,1,4Notes
It works only with a stream of strings (CharSequence), so numbers and objects are first converted with map(String::valueOf). For an existing collection of strings without a stream, String.join(", ", list) works.
See also
- Stream.collect() — Gathers stream elements into a collection, a string or another structure.
- Stream.map() — Transforms every element of a stream.
Related recipes
In the tutorial
- Collectors — The collect method and the Collectors class — toList, toSet, toMap, joining, counting, summingInt, averagingDouble and the duplicate key error.