Stream Iterate Bounded Sequence

Walk cursor-paginated APIs with the three-argument Stream.iterate, where the hasNext predicate ends the sequence exactly when the next token is null.

JavaData Fetching

Code

snippet
import java.util.List;
import java.util.stream.Stream;

public class PageWalker {

    // 模拟游标分页接口:给一个 token,返回该页数据与下一页 token
    record Page(List<String> items, String nextToken) {}

    static Page fetch(String token) {
        return switch (token) {
            case "t1" -> new Page(List.of("a1", "a2"), "t2");
            case "t2" -> new Page(List.of("a3", "a4"), "t3");
            default -> new Page(List.of("a5"), null);
        };
    }

    public static void main(String[] args) {
        // Stream.iterate(seed, hasNext, next)(Java 9+):
        // hasNext 谓词为 false 时序列自然终止,不需要 limit() 猜页数
        List<String> allItems = Stream.iterate(
                        fetch("t1"),
                        page -> page.nextToken() != null,
                        page -> fetch(page.nextToken()))
                .flatMap(p -> p.items().stream())
                .toList();
        System.out.println(allItems);

        // 对照:无界源配上界谓词,同样在谓词处收敛
        System.out.println(Stream.iterate(1, n -> n < 100, n -> n * 3).toList());
    }
}

Inside the snippet

Stream Iterate Bounded Sequence reduces to the classes PageWalker and Page and the functions fetch and main.

Data flows through a stream pipeline where each stage returns a new view rather than mutating.

Putting it to use

The main signature reads static Page fetch(String token)

Running the file executes main, which drives fetch in order.

Core lines

return switch (token) {
case "t1" -> new Page(List.of("a1", "a2"), "t2");
case "t2" -> new Page(List.of("a3", "a4"), "t3");
default -> new Page(List.of("a5"), null);
};
.flatMap(p -> p.items().stream())
.toList();

FAQ

How do you run Stream Iterate Bounded Sequence?
Run the file on its own; every call resolves against the standard surface it already imports.