Java Stream Merge: Concat Method Guide
In Java, you can merge streams using the concat() method from the Stream class. This method takes two streams as input and returns a new stream containing elements from both input streams.
Here is a sample code:
import java.util.stream.Stream;
public class StreamMergeExample {
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);
}
}
The output result is:
A
B
C
D
E
F
In the example, we created two Stream objects, stream1 and stream2, which each contain strings “A”, “B”, “C” and “D”, “E”, “F” respectively. We then used the concat() method to merge the two Streams into a new Stream called mergedStream. Finally, we used the forEach() method to iterate and output the elements in the merged Stream.
It is important to note that a Stream object can only be consumed (operated on) once. In the example, we only called the forEach() method once to output the elements in the merged Stream. If forEach() is called again, an exception will be thrown. If you need to perform multiple operations on a Stream, you can create a new Stream object to work with.