Here we will see how to Merge Streams in Java 8.

How to Merge Streams:

Concatenating of streams in java 8 is achieved by using stream concat() method. Stream API has given us a static way Stream.concat() for merging streams.

Syntax:

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

concat() method creates a lazily concatenated stream which contains all elements of the first stream followed by the second stream.

How to Merge Streams Example:

Here is a simple example of merging two different streams.

MergeTwoStreams.java
import java.util.stream.Stream;

class MergeTwoStreams {
    public static void main(String[] args) {
        Stream<String> stream1 = Stream.of("1", "2", "3");
        Stream<String> stream2 = Stream.of("A", "B", "C");
        Stream<String> stream1_stream2 = Stream.concat(stream1, stream2);
        System.out.println(stream1_stream2.collect(Collectors.toList()));
    }
}

Output:

Terminal
[1, 2, 3, A, B, C]

How to Merge Multiple Streams:

On the above example, we have seen merging the two streams, and we can also merge 2 or more different streams using Stream.concat() method.

MergingMultipleStreams.java
import java.util.stream.Stream;

public class MergingMultipleStreams {
    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> stream1_stream2_stream3 = Stream.concat(Stream.concat(stream1, stream2),stream3);
        System.out.println(stream1_stream2_stream3.collect(Collectors.toList()));

    }
}

Output:

Terminal
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Merging Streams and Removing Duplicates:

It is a prevalent scenario to remove the duplicate elements from a stream. Stream.distinct() method is used to remove duplicates or get the distinct elements from a stream.

StreamDistinct.java
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamDistinct {
    public static void main(String[] args) {

        Stream<Integer> stream1 = Stream.of(1,2,3);
        Stream<Integer> stream2 = Stream.of(4,2,1);
        Stream<Integer> stream3 = Stream.of(3,5,6);
        Stream<Integer> stream1_stream2_stream3 = Stream.concat(Stream.concat(stream1, stream2),stream3);
        System.out.println(stream1_stream2_stream3.distinct().collect(Collectors.toList()));

    }
}

Output:

Terminal
[1, 2, 3, 4, 5, 6]

Done!

Happy Learning 🙂

About the Author:

Avatar
Founder of onlinetutorialspoint.com Love Java, Python, Shell and opensource frameworks. Follow him on twitter and facebook for latest updates.

Leave A Comment