The source of a stream can be from combining two or more other streams. Streams can be concatenated using the static concat method. This method is illustrated below where two integer streams are created. The first stream consists of the first 10 even numbers and the second stream consists of the first 10 odd numbers. The limit method restricts the output of the iterate methods to 10 elements. The concat method takes two streams and returns a third. Stream<Integer> evenStream = Stream.iterate(2, n -> n+2).limit(10); Stream<Integer> oddStream = Stream.iterate(1, n -> n+2).limit(10); Stream<Integer> numbers = Stream.concat(evenStream,oddStream); numbers.forEach(n -> System.out.print(n + ” “));
The output will be as follows: 2 4 6 8 10 12 14 16 18 20 1 3 5 7 9 11 13 15 17 19 Generating an Empty Stream An empty stream is one that does not contain any elements. It may be returned by some methods or can be created using the empty method as shown below: Stream<Integer> empty = Stream.empty(); If the Stream interface’s count method returns 0, then the stream is empty. Using Stream Methods There are numerous methods that can be applied to a stream. These are typically used for such activities as listing elements of a stream, creating new streams after transforming existing elements, or filtering out certain elements. The examples used for the Stream interface methods will, at times, use methods not yet covered. This is sometimes necessary to demonstrate the utility of a technique. When this occurs, a brief introduction to the method will be presented. A more complete coverage can be found in the corresponding method’s section. In this section we will examine most of the Stream interface’s methods.