Following concatenating two arraylists , if you are processing data from microservices you may need to put together streams to process and this example will show how to join a stream of strings, IntStream , LongStream , and DoubleStream .
The snippets below will create stream and then use Stream.concat
which will lazily concatenated stream whose elements are 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. When the resulting stream is closed, the close handlers for both input streams are invoked.
Join Stream of Strings @Test
public void join_stream () {
Stream < String > stream1 = Stream . of ( "one" , "two" );
Stream < String > stream2 = Stream . of ( "three" , "four" );
Stream . concat ( stream1 , stream2 ). forEach ( e -> System . out . println ( e ));
}
Output
one
two
three
four
Join IntStream @Test
public void join_intstream () {
IntStream intStream1 = IntStream . of ( 1 , 2 );
IntStream intStream2 = IntStream . of ( 3 , 4 );
IntStream . concat ( intStream1 , intStream2 ). forEach (
e -> System . out . println ( e ));
}
Output
1
2
3
4
Join LongStream @Test
public void join_longstreamstream () {
LongStream longStream1 = LongStream . of ( 5 , 6 );
LongStream longStream2 = LongStream . of ( 7 , 8 );
LongStream . concat ( longStream1 , longStream2 ). forEach (
e -> System . out . println ( e ));
}
Output
5
6
7
8
Join DoubleStream @Test
public void join_doublestream_stream () {
DoubleStream doubleStream1 = DoubleStream . of ( 9 , 10 );
DoubleStream doubleStream2 = DoubleStream . of ( 11 , 12 );
DoubleStream . concat ( doubleStream1 , doubleStream2 ). forEach (
e -> System . out . println ( e ));
}
Output
9.0
10.0
11.0
12.0
Concatenate java 8 stream posted by Justin Musgrove on 29 August 2015
Tagged: java and java-stream
Share on: Facebook Google+
All the code on this page is available on github:
ConcatenateStream.java