Java Stream concat() Method Tutorial

In this section, we will learn what the Stream concat() method is and how to use it in Java.

What is Java Stream concat() Method?

The Java Stream concat() method is used to concatenate two streams and produce a new one that is the combination of both.

Java concat() Method Syntax:

static <T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b)

concat() Method Parameters:

The method takes two arguments:

The first argument is a reference to a stream that we want to concatenate it with another stream.

The second argument is a reference to a stream that we want to concatenate it with the first stream that we’ve set as the first argument of the method.

concat() Method Return Value:

The return value of this method is a new stream that contains the elements of both streams (both arguments) of the method.

Note: the elements of the first stream (first argument) come first and after that are the elements of the second stream (second argument of the method).

Example: using Stream concat() method

import java.util.stream.Stream;
class Main{
    public static void main(String[] args) {
        Stream<Integer> stream = Stream.of(1,2,3,4,5);
        Stream<Integer> stream2 = Stream.of(6,7,8,9,10);

        Stream<Integer> concat = Stream.concat(stream, stream2);
        concat.forEach(e->System.out.print(e+", "));
    }
}

Output:

1, 2, 3, 4, 5, 6, 7, 8, 9, 10,

Leave a Reply