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
parallelif one of the input streams isparallel. -
This method creates a lazily concatenated stream, which means the
concatmethod 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 twostreams:stream1with elements1,2,3.stream2with elements4,5,6
-
Called the
Stream.concatmethod with the created stream as an argument. -
The
concatmethod will return a stream that contains both the elements ofstream1andstream2. -
Collected the stream as a
Listusing thecollect(Collectors.toList())method. The argumentCollectors.toList()tells theconcatmethod to collect the stream asList.
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.