Java Reference
In-Depth Information
Empty Streams
An empty stream is a stream with no elements. The Stream interface contains an empty() static method to create an
empty sequential stream.
// Creates an empty stream of strings
Stream<String> stream = Stream.empty();
The IntStream , LongStream , and DoubleStream interfaces also contain an empty() static method to create an
empty stream of primitive types.
// Creates an empty stream of integers
IntStream numbers = IntStream.empty();
Streams from Functions
An infinite stream is a stream with a data source capable of generating infinite number of elements. Note that I am
saying that the data source should be “capable of generating” infinite number of elements, rather the data source
should have or contain an infinite number of elements. It is impossible to generate and store an infinite number of
elements of any kind because of memory and time constraints. However, it is possible to have a function that can
generate infinite number of values on demand.
The Stream interface contains the following two static methods to generate an infinite stream:
<T> Stream<T> iterate(T seed, UnaryOperator<T> f)
<T> Stream<T> generate(Supplier<T> s)
The iterator() method creates a sequential ordered stream whereas the generate() method creates a
sequential unordered stream. The following sections will show you how to use these methods.
The stream interfaces for primitive values IntStream , LongStream , and DoubleStream also contain iterate()
and generate() static methods that take parameters specific to their primitive types. For example, these methods are
defined as follows in the IntStream interface:
IntStream iterate(int seed, IntUnaryOperator f)
IntStream generate(IntSupplier s)
Using the Stream.iterate( ) Method
The iterator() method takes two arguments: a seed and a function. The first argument is a seed that is the first
element of the stream. The second element is generated by applying the function to the first element. The third
element is generated by applying the function on the second element and so on. Its elements are seed , f(seed) ,
f(f(seed)) , f(f(f(seed))) , and so on. The following statement creates an infinite stream of natural numbers and an
infinite stream of all odd natural numbers:
// Creates a stream of natural numbers
Stream<Long> naturalNumbers = Stream.iterate(1L, n -> n + 1);
// Creates a stream of odd natural numbers
Stream<Long> oddNaturalNumbers = Stream.iterate(1L, n -> n + 2);
What do you do with an infinite stream? You understand that it is not possible to consume all elements of an
infinite stream. This is simply because the stream processing will take forever to complete. Typically, you convert the
infinite stream into a fixed-size stream by applying a limit operation that truncates the input stream to be no longer
 
Search WWH ::




Custom Search