Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Streams and Functional

Collectors.joining() method

Reference for Java Collectors.joining(): concatenate stream elements into one String with a delimiter, prefix and suffix, and know which element types it accepts.

Collectors.joining() is a collector that concatenates the elements of a stream into a single String. It comes in three forms: no arguments (plain concatenation), a delimiter, and a delimiter with a prefix and suffix.

It works on a Stream<? extends CharSequence>, so the elements must be strings (or StringBuilders, and so on). Convert other types first with map(String::valueOf). Internally it uses a StringJoiner, so it is efficient for large inputs.

Java
String csv = Stream.of("a", "b", "c").collect(Collectors.joining(", "));
// "a, b, c"

Try it

Java Delimiter, prefix and suffix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java Non-strings and downstream use

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Syntax

Java
static Collector<CharSequence, ?, String> joining()

static Collector<CharSequence, ?, String> joining(CharSequence delimiter)

static Collector<CharSequence, ?, String> joining(
        CharSequence delimiter, CharSequence prefix, CharSequence suffix)
Name Description
delimiter Inserted between neighbouring elements. Not added before the first or after the last.
prefix Placed at the very beginning of the result.
suffix Placed at the very end of the result.

Returns: a collector that produces the joined String. For an empty stream the result is prefix + suffix (an empty string without them).

Usage notes

  • Strings only. Stream<Integer> does not compile with joining(); map to strings first with String::valueOf or Object::toString.
  • Null elements are not rejected: they are appended as the four characters null. Filter them out with Objects::nonNull if that is not wanted.
  • Empty stream: the prefix and suffix still appear, which can surprise you when building something like "(...)". Check emptiness first if an empty result must stay empty.
  • Equivalents: String.join() does the same for an existing Iterable or varargs without a stream, and StringJoiner is the underlying tool.
  • Order: the result follows the stream's encounter order. In a parallel stream over an ordered source the order is still preserved.
  • Escaping: no quoting or escaping is applied. If elements can contain the delimiter (CSV!) escape them yourself.
  • Complexity: linear in the total length of the output.