Concatenate Streams

suggest change

Variable declaration for examples:

Collection<String> abc = Arrays.asList("a", "b", "c");
Collection<String> digits = Arrays.asList("1", "2", "3");
Collection<String> greekAbc = Arrays.asList("alpha", "beta", "gamma");

Example 1 - Concatenate two Streams

final Stream<String> concat1 = Stream.concat(,;

// prints: abc123

Example 2 - Concatenate more than two Streams

final Stream<String> concat2 = Stream.concat(

System.out.println(concat2.collect(Collectors.joining(", ")));
// prints: a, b, c, 1, 2, 3, alpha, beta, gamma

Alternatively to simplify the nested concat() syntax the Streams can also be concatenated with flatMap():

final Stream<String> concat3 = Stream.of(,,
    .flatMap(s -> s);
    // or `.flatMap(Function.identity());` (java.util.function.Function)

System.out.println(concat3.collect(Collectors.joining(", ")));
// prints: a, b, c, 1, 2, 3, alpha, beta, gamma

Be careful when constructing Streams from repeated concatenation, because accessing an element of a deeply concatenated Stream can result in deep call chains or even a StackOverflowException.

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents