Sub topic 16
Infinite Streams with iterate and generate
Most streams come from something that has an end, like a list with five items. Java also lets you build an infinite stream, which is a stream that can keep producing new elements forever. That sounds risky, but streams are lazy. A stream only makes an element when a later step asks for one. So you can describe an endless sequence and then take just the part you need.
Two ways to make an endless stream
Java gives you two factory methods for this.
| Method | What it needs | How each element is made |
|---|---|---|
| `Stream.iterate(seed, f)` | A starting value and a function | Each element is made from the one before it |
| `Stream.generate(supplier)` | A supplier | Each element is made fresh, with no link to the last one |
A seed is the first value of the sequence. A supplier is a lambda that takes no input and returns a value, such as () -> "hello".
Using iterate
Stream.iterate(1, n -> n * 2) starts at 1. It then applies n -> n * 2 to get the next value: 1, 2, 4, 8, and so on. The limit(5) step makes the stream stop after five elements.
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class InfiniteExample {
public static void main(String[] args) {
List<Integer> powersOfTwo = Stream.iterate(1, n -> n * 2)
.limit(5)
.collect(Collectors.toList());
System.out.println(powersOfTwo); // [1, 2, 4, 8, 16]
}
}Using generate
generate calls the supplier again every time the stream needs another element. It works well for repeated values or random values.
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class GenerateExample {
public static void main(String[] args) {
List<String> greetings = Stream.generate(() -> "hello")
.limit(3)
.collect(Collectors.toList());
System.out.println(greetings); // [hello, hello, hello]
}
}If you swap in () -> Math.random(), you get three random numbers, and they change on every run.
Always add a stopping point
An infinite stream needs a step that ends it. The usual choice is limit(n), which keeps only the first n elements. Short-circuiting terminal operations such as findFirst or anyMatch also stop the stream once they have their answer.
Exercise
Write a pipeline that uses Stream.iterate to produce a list of the first four multiples of 3. What does it print?
Show answer
List<Integer> result = Stream.iterate(3, n -> n + 3).limit(4).collect(Collectors.toList()); System.out.println(result); prints [3, 6, 9, 12]. The seed is 3, each step adds 3, and limit(4) stops the stream after four elements.
Exercise
What happens when you run Stream.generate(() -> "x").forEach(System.out::println); and why?
Show answer
It prints "x" over and over and never stops. generate makes an infinite stream, and forEach asks for every element. There is no limit or short-circuiting operation to end the stream.