1+ package com .baeldung .stream ;
2+
3+ import org .junit .Test ;
4+
5+ import java .util .Arrays ;
6+ import java .util .function .Function ;
7+ import java .util .stream .Collectors ;
8+ import java .util .stream .Stream ;
9+
10+ import static org .junit .Assert .assertEquals ;
11+
12+ public class MergeStreamsTest {
13+
14+ @ Test
15+ public void givenTwoStreams_whenMergingStreams_thenResultingStreamContainsElementsFromBothStreams () {
16+ Stream <Integer > stream1 = Stream .of (1 , 3 , 5 );
17+ Stream <Integer > stream2 = Stream .of (2 , 4 , 6 );
18+
19+ Stream <Integer > resultingStream = Stream .concat (stream1 ,
20+ stream2 );
21+
22+ assertEquals (Arrays .asList (1 , 3 , 5 , 2 , 4 , 6 ),
23+ resultingStream .collect (Collectors .toList ()));
24+ }
25+
26+ @ Test
27+ public void givenThreeStreams_whenMergingStreams_thenResultingStreamContainsElementsFromAllStreams () {
28+ Stream <Integer > stream1 = Stream .of (1 , 3 , 5 );
29+ Stream <Integer > stream2 = Stream .of (2 , 4 , 6 );
30+ Stream <Integer > stream3 = Stream .of (18 , 15 , 36 );
31+
32+ Stream <Integer > resultingStream = Stream .concat (Stream .concat (stream1 ,
33+ stream2 ),
34+ stream3 );
35+
36+ assertEquals (Arrays .asList (1 , 3 , 5 , 2 , 4 , 6 , 18 , 15 , 36 ),
37+ resultingStream .collect (Collectors .toList ()));
38+ }
39+
40+ @ Test
41+ public void givenFourStreams_whenMergingStreams_thenResultingStreamContainsElementsFromAllStreams () {
42+ Stream <Integer > stream1 = Stream .of (1 , 3 , 5 );
43+ Stream <Integer > stream2 = Stream .of (2 , 4 , 6 );
44+ Stream <Integer > stream3 = Stream .of (18 , 15 , 36 );
45+ Stream <Integer > stream4 = Stream .of (99 );
46+
47+ Stream <Integer > resultingStream = Stream .of (stream1 , stream2 , stream3 , stream4 ).flatMap (Function .identity ());
48+
49+ assertEquals (Arrays .asList (1 , 3 , 5 , 2 , 4 , 6 , 18 , 15 , 36 , 99 ),
50+ resultingStream .collect (Collectors .toList ()));
51+
52+ }
53+ }
0 commit comments