What is the concat() method of Stream Interface?

The concat() method is a static method of the Stream Interface that can be used to merge two streams into a single stream.

  • The merged stream contains all the elements of the first stream, followed by all the elements of the second stream.

  • If both the streams are ordered, then the merged stream will be ordered.

  • The merged stream is parallel if one of the input streams is parallel.

  • This method creates a lazily concatenated stream, which means the concat method is not evaluated unless the terminal operation is invoked.

Syntax

static <T> Stream<T> concat(Stream<? extends T> firstStream,
                            Stream<? extends T> secondStream)

Example

import java.util.stream.Stream;
import java.util.stream.Collectors;
class HelloWorld {
public static void main(String[] args) {
Stream<Integer> stream1 = Stream.of(1, 2, 3);
Stream<Integer> stream2 = Stream.of(4, 5, 6);
Stream<Integer> mergedStream = Stream.concat(stream1, stream2);
System.out.println( mergedStream.collect(Collectors.toList() ));
}
}

In the code above, we have:

  • Used the Stream.of() method to create two streams:
    • stream1 with elements 1,2,3.
    • stream2 with elements 4,5,6
  • Called the Stream.concat method with the created stream as an argument.

  • The concat method will return a stream that contains both the elements of stream1 and stream2.

  • Collected the stream as a List using the collect(Collectors.toList()) method. The argument Collectors.toList() tells the concat method to collect the stream as List.

Merge multiple streams

import java.util.stream.Stream;
import java.util.stream.Collectors;
class HelloWorld {
public static void main(String[] args) {
Stream<Integer> stream1 = Stream.of(1, 2, 3);
Stream<Integer> stream2 = Stream.of(4, 5, 6);
Stream<Integer> stream3 = Stream.of(7, 8, 9);
Stream<Integer> mergedStream = Stream.concat(stream1, stream2);
mergedStream = Stream.concat(mergedStream, stream3);
System.out.println( mergedStream.collect(Collectors.toList() ));
}
}

In the code above, we have created three Stream objects. First, we merged stream1 and stream2 by calling:

Stream<Integer> mergedStream = Stream.concat(stream1, stream2); 

Then, the mergedStream is merged with the stream3.

mergedStream = Stream.concat(mergedStream, stream3);

Now, the merged stream contains elements of all three streams.

Free Resources