Concat Streams in Java 8

You may often need to concat or merge two streams. In the Stream class, there is a static method concat() that can be used for this purpose.

Merge Two Streams

String[] arr1 = { "a", "b", "c", "d" };
String[] arr2 = { "e", "f", "g" };
Stream<String> stream1 = Stream.of(arr1);
Stream<String> stream2 = Stream.of(arr2);
 
Stream<String> stream3 = Stream.concat(stream1, stream2);
String[] arr = stream3.toArray(String[]::new);
System.out.println(Arrays.toString(arr));

Output:

[a, b, c, d, e, f, g]

Merge a Filtered Stream to Another

If you need to filter a stream before concatting to another stream:

String[] arr1 = { "abc", "bcd", "cdef", "defgh" };
String[] arr2 = { "af", "fg", "gh" };
Stream<String> stream1 = Stream.of(arr1);
Stream<String> stream2 = Stream.of(arr2);
 
Stream<String> stream3 = Stream.concat(stream1.filter(x -> x.length()<4), stream2);
String[] arr = stream3.toArray(String[]::new);
System.out.println(Arrays.toString(arr));

Output:

[abc, bcd, af, fg, gh]

Merger More Than 2 Streams

String[] arr1 = { "a", "b", "c", "d" };
String[] arr2 = { "e", "f", "g" };
String[] arr3 = { "h", "i", "j" };
Stream<String> stream1 = Stream.of(arr1);
Stream<String> stream2 = Stream.of(arr2);
Stream<String> stream3 = Stream.of(arr3);
 
Stream<String> stream = Stream.concat(Stream.concat(stream1, stream2), stream3);
String[] arr = stream.toArray(String[]::new);
System.out.println(Arrays.toString(arr));

Output:

[a, b, c, d, e, f, g, h, i, j]

Note that elements returned by Stream.concat() method is ordered. For example, the following two lines returns the same result:

Stream.concat(Stream.concat(stream1, stream2), stream3);
Stream.concat(stream1, Stream.concat(stream2, stream3));

But the result for the following two are different.

Stream.concat(Stream.concat(stream1, stream2), stream3); //[a, b, c, d, e, f, g, h, i, j]
Stream.concat(Stream.concat(stream2, stream1), stream3); //[e, f, g, a, b, c, d, h, i, j]

Use Stream.of(…).flatMap() for Merging

To make the code more readable, you can also use Stream.of() method to merge more than two streams.

String[] arr1 = { "a", "b", "c", "d" };
String[] arr2 = { "e", "f", "g" };
String[] arr3 = { "h", "i", "j" };
Stream<String> stream1 = Stream.of(arr1);
Stream<String> stream2 = Stream.of(arr2);
Stream<String> stream3 = Stream.of(arr3);
 
//use Stream.of(T... values)
Stream<String> stream = Stream.of(stream1, stream2, stream3).flatMap(x -> x);
 
String[] arr = stream.toArray(String[]::new);
System.out.println(Arrays.toString(arr));

4 thoughts on “Concat Streams in Java 8”

  1. How do you merge 2 list containing alternate number using stream
    list a = 1,2,3
    list b = 7,8,9

    merge list c = 1,7,2,8,3,9

  2. Nice post. I just want to add an extra information, when using flatmap method, the limit doesn’t work. We must use Stream.concat.

Leave a Comment