In Java 8, we can use Stream.iterate to create stream values on demand, so called infinite stream.
1. Stream.iterate
1.1 Stream of 0 – 9
//Stream.iterate(initial value, next value)
Stream.iterate(0, n -> n + 1)
.limit(10)
.forEach(x -> System.out.println(x));
Output
1.2 Stream of odd numbers only.
Stream.iterate(0, n -> n + 1)
.filter(x -> x % 2 != 0) //odd
.limit(10)
.forEach(x -> System.out.println(x));
Output
11
13
15
17
19
1.3 A classic Fibonacci example.
Stream.iterate(new int[]{0, 1}, n -> new int[]{n[1], n[0] + n[1]})
.limit(20)
.map(n -> n[0])
.forEach(x -> System.out.println(x));
Output
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
1.4 Sum all the Fibonacci values.
int sum = Stream.iterate(new int[]{0, 1}, n -> new int[]{n[1], n[0] + n[1]})
.limit(10)
.map(n -> n[0]) // Stream
.mapToInt(n -> n)
.sum();
System.out.println("Fibonacci 10 sum : " + sum);
Output
Fibonacci 10 sum : 88
2. Java 9
The stream.iterate was enhanced in Java 9. It supports a predicate (condition) as second argument, and the stream.iterate will stop if the predicate is false.
2.1 Stop the stream iteration if n >= 20
Stream.iterate(1, n -> n < 20 , n -> n * 2)
.forEach(x -> System.out.println(x));
Output
16
References