Merge Streams In Java

In this tutorial, I am showing how to merge multiple streams in java using different ways.

Note: Stream.concat(stream1,stream2) method is useful when you have 2 streams and if you have more than 2 streams, you can use Stream.of(stream1, stream2, stream3, stream4) method.



Merge two Streams

The best way to merge two streams, you can use Stream.concat(stream1,stream2) method. You can see example below.

package com.javatips;

import java.util.stream.Stream;

public class MergeStream {

    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(stream -> System.out.println(stream));
	
	
    }

}


Output

A
B
C
D
E
F


Merge Multiple Streams

When you have to merge more than 2 streams, you can use Stream.of(stream1, stream2, stream3, stream4)

package com.javatips;

import java.util.stream.Stream;

public class MergeStream {

    public static void main(String[] args) {
	Stream<String> stream1 = Stream.of("A","B","C");
	Stream<String> stream2 = Stream.of("D","E","F");
	Stream<String> stream3 = Stream.of("G","H","I");
	Stream<String> stream4 = Stream.of("J","K","L");
	
	Stream<String> mergedStream = Stream.of(stream1, stream2, stream3, stream4).flatMap(i -> i);
	mergedStream.forEach(stream -> System.out.println(stream));
    }

}


Output

A
B
C
D
E
F
G
H
I
J
K
L












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