You can use a function that can generate infinite number of values on demand as the source of stream.
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)
iterator() method creates a sequential ordered stream whereas the generate() method creates a sequential unordered stream.
IntStream, LongStream, and DoubleStream also contain iterate() and generate() static methods that take parameters specific to their primitive types.
IntStream iterate(int seed, IntUnaryOperator f) IntStream generate(IntSupplier s)
iterator() method takes two arguments: a seed and a function.
The first argument is a seed that is the first element of the stream.
Its elements are seed, f(seed), f(f(seed)), f(f(f(seed))), and so on.
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);
You convert the infinite stream into a fixed-size stream by applying a limit operation.
The limit operation is an intermediate operation that produces another stream.
You apply the limit operation using the limit(long maxSize) method of the Stream interface.
The following code creates a stream of the first 10 natural numbers:
// Creates a stream of the first 10 natural numbers Stream<Long> tenNaturalNumbers = Stream.iterate(1L, n -> n + 1) .limit(10);
You can apply a forEach operation on a stream using the forEach(Consumer<? super T> action) method.
It is a terminal operation. The following code prints the first five odd natural numbers on the standard output:
Stream.iterate(1L, n -> n + 2) .limit(5) .forEach(System.out::println);