Sub topic 16
Infinite Streams with iterate and generate
Most streams you have seen so far come from a list or an array, so they hold a fixed number of elements. Java also lets you build a stream that never runs out. This chapter shows how to create these infinite streams, how to stop them safely, and which mistakes make a program hang.
What Is an Infinite Stream?
An infinite stream is a stream with no last element. It never stores all its values in memory. It works out each new value only when the next step of the pipeline asks for one.
That is only possible because streams are lazy. Lazy means a stream does no work until a terminal operation asks for elements (you saw this in "Why Streams Are Lazy"). An infinite stream relies on that rule. It hands out one value at a time, as long as someone keeps asking.
So the real question is how to stop asking. You use a short-circuiting operation, which is an operation that can finish without looking at every element. The most common one is limit(n), which passes along the first n elements and then stops.
Java gives you two ways to build an infinite stream:
| Method | What it needs | How each value is made |
|---|---|---|
| `Stream.iterate(seed, f)` | A starting value and a function | Apply `f` to the previous value |
| `Stream.generate(s)` | A supplier (a function with no input) | Call `s` again, with no link to earlier values |
Building a Sequence with Stream.iterate
Stream.iterate takes two arguments:
- The seed, which is the first element.
- A function that turns one element into the next one.
The stream starts with the seed, then the function applied to the seed, then the function applied to that result, and so on forever.
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]
}
}Here is what happens, step by step:
Stream.iterate(1, n -> n * 2)describes the sequence 1, 2, 4, 8, ... but computes nothing yet.limit(5)says "let only five elements through."collectis the terminal operation. It starts pulling values.- After the fifth value,
limittells the pipeline it is finished, soiterateis never asked for a sixth.
Finding a value instead of counting
You don't always know how many elements you need. Sometimes you want the first value that meets a condition. Then filter plus findFirst works, because findFirst also short-circuits.
import java.util.stream.Stream;
public class FirstOverThousand {
public static void main(String[] args) {
int first = Stream.iterate(1, n -> n * 2)
.filter(n -> n > 1000)
.findFirst()
.get();
System.out.println(first); // 1024
}
}Calling get() is safe here only because a matching value is sure to exist. If no element ever matched, findFirst would keep searching forever.
The three-argument iterate (Java 9 and later)
Java 9 added a version of iterate that works like a for loop. It takes a seed, a condition (called a predicate, a function that returns true or false), and the step function. The stream ends as soon as the condition is false, so it is no longer infinite.
import java.util.List;
import java.util.stream.Stream;
public class IterateWithCondition {
public static void main(String[] args) {
// Same as: for (int n = 1; n <= 16; n = n * 2)
List<Integer> powers = Stream.iterate(1, n -> n <= 16, n -> n * 2)
.toList();
System.out.println(powers); // [1, 2, 4, 8, 16]
}
}toList() requires Java 16. On Java 9 to 15, use collect(Collectors.toList()) instead.
Producing Values with Stream.generate
Stream.generate takes a Supplier. A supplier is a function that takes no input and returns a value. The stream calls it again every time it needs another element. Each value has no connection to the one before it.
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class GenerateExample {
public static void main(String[] args) {
// The same constant value, three times
List<String> pings = Stream.generate(() -> "ping")
.limit(3)
.collect(Collectors.toList());
System.out.println(pings); // [ping, ping, ping]
// Five random dice rolls between 1 and 6
Random random = new Random();
List<Integer> rolls = Stream.generate(() -> random.nextInt(6) + 1)
.limit(5)
.collect(Collectors.toList());
System.out.println(rolls); // for example [3, 6, 1, 1, 4]
}
}Pick generate when each value stands alone, such as random numbers, fresh objects, or a repeated default. Pick iterate when each value depends on the previous one.
Primitive Versions
The primitive streams from the previous chapter have their own iterate and generate. They avoid boxing, which is wrapping an int in an Integer object.
import java.util.stream.IntStream;
public class IntIterateExample {
public static void main(String[] args) {
int sumOfOdds = IntStream.iterate(1, n -> n + 2)
.limit(4)
.sum();
System.out.println(sumOfOdds); // 1 + 3 + 5 + 7 = 16
}
}Edge Cases That Catch Beginners
Operations that need every element
Some operations must see the whole stream before they can give anything back. On an infinite stream they never finish, and your program hangs. Examples:
sorted(), because it can't know the smallest value until it has seen them all.count(),collect(...),forEach(...), andreduce(...)with nolimitbefore them.
The order of operations matters. limit must come before any operation that needs all elements.
import java.util.List;
import java.util.stream.Stream;
public class OrderMatters {
public static void main(String[] args) {
// Works: limit makes the stream finite, then sorted runs
List<Integer> ok = Stream.iterate(10, n -> n - 3)
.limit(4)
.sorted()
.toList();
System.out.println(ok); // [1, 4, 7, 10]
// Would hang forever: sorted waits for an end that never comes
// Stream.iterate(10, n -> n - 3).sorted().limit(4).toList();
}
}distinct with too few unique values
distinct() removes repeated values. If you ask for more unique values than the source can ever produce, limit never reaches its count.
Number overflow
An int can only hold values up to 2,147,483,647. If iterate keeps doubling, the value overflows. 2 to the power of 31 wraps around to -2,147,483,648, and every value after that is 0. Java gives you no error. Keep your limit small enough, or switch to long or LongStream for bigger numbers.
Exercises
Exercise
Write a pipeline that uses Stream.iterate to produce the first six multiples of 5 (5, 10, 15, 20, 25, 30) and collects them into a list.
Show answer
Stream.iterate(5, n -> n + 5).limit(6).collect(Collectors.toList()) gives [5, 10, 15, 20, 25, 30]. The seed is 5, each step adds 5, and limit(6) stops the stream after six elements.
Exercise
Why does Stream.iterate(1, n -> n + 1).sorted().limit(3).toList() hang, and how do you fix it?
Show answer
sorted() must see every element before it can output any, and the stream has no end, so sorted waits forever. Move limit before sorted: Stream.iterate(1, n -> n + 1).limit(3).sorted().toList() returns [1, 2, 3].
Exercise
You want ten random numbers. Should you use iterate or generate, and why?
Show answer
Use generate, for example Stream.generate(() -> random.nextInt(100)).limit(10). Each random number doesn't depend on the previous one, and that is the case generate is built for. iterate fits when each value is computed from the one before.