Java Stream concat() With Examples

If you want to merge two streams you can use concat() method in Java Stream API.

Syntax of concat() method

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

Here a represents the first stream and b represents the second stream. Method returns a stream consisting all the elements of the first stream followed by all the elements of the second stream.

The resulting stream is ordered if both of the input streams are ordered, and parallel if either of the input streams is parallel.

concat() method Java examples

1. Using concat() method to merge streams of Strings.

public class ConcatDemo {
  public static void main(String[] args) {
    Stream<String> stream1 = Stream.of("A", "B", "C");
    Stream<String> stream2 = Stream.of("D", "E", "F");
    Stream<String> mergedStream = Stream.concat(stream1, stream2);
    mergedStream.forEach(System.out::println);
  }
}

Output

A
B
C
D
E
F

2. Using concat method to merge more than 2 streams. You can also layer the concat() method to merge more than two streams, in the following example 4 streams are concatenated.

public class ConcatDemo {
  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> stream4 = Stream.of(10, 11, 12);
    Stream<Integer> mergedStream = Stream.concat(stream1, 
            Stream.concat(Stream.concat(stream2, stream3), stream4));
    mergedStream.forEach(e -> System.out.print(e + " "));
  }
}

Output

1 2 3 4 5 6 7 8 9 10 11 12 

3. Using concat() with other stream operations. A very common scenario is to merge two streams and get only the distinct elements, that can be done by using distinct() in Java stream.

public class ConcatDemo {
  public static void main(String[] args) {
    Stream<Integer> stream1 = Stream.of(1, 2, 3, 4, 5, 6);
    Stream<Integer> stream2 = Stream.of(4, 4, 3, 1, 8, 6);

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

Output

1 2 3 4 5 6 8 

Related Posts

That’s all for the topic Java Stream concat() With Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

Share this post:

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.