Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Streams and Functional

Java Stream.iterate() and generate()

Reference for Java Stream.iterate() and Stream.generate(): build infinite or bounded sequences from a seed, with the three-argument form (Java 9).

Stream.iterate() builds a sequence from a seed and a function that produces each next element from the previous one: seed, f(seed), f(f(seed)), and so on. The two-argument form is infinite, so you must limit it with limit(), takeWhile() or a short-circuiting terminal such as findFirst().

Java 9 added a three-argument form with a hasNext predicate, which works like a classic for loop and ends by itself. Stream.generate(supplier) is the related factory for sequences that do not depend on the previous element.

Java
Stream.iterate(1, n -> n * 2).limit(5);      // 1, 2, 4, 8, 16
Stream.iterate(0, n -> n < 10, n -> n + 3);  // 0, 3, 6, 9

Try it

Java Infinite and bounded iteration

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java generate() and a counting loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Syntax

Java
static <T> Stream<T> iterate(T seed, UnaryOperator<T> next)
static <T> Stream<T> iterate(T seed, Predicate<? super T> hasNext, UnaryOperator<T> next)
static <T> Stream<T> generate(Supplier<? extends T> s)
Name Description
seed The first element.
hasNext Three-argument form only: while it returns true the element is produced; the stream ends at the first false.
next Computes the next element from the previous one.
s For generate(): supplies each element.

Returns: a sequential, ordered Stream<T> (iterate) or an unordered one (generate).

Usage notes

  • Always bound the two-argument forms. Stream.iterate(1, n -> n + 1).forEach(...) never ends.
  • Lazy: next is called only when an element is needed, so limit(n) calls it about n - 1 times.
  • Predicate vs takeWhile: the three-argument form tests the seed too and never calls next after the end; with takeWhile the next value was already computed.
  • Stateful suppliers: generate() with a counter works only sequentially. For numbers, prefer IntStream.range() or IntStream.iterate().
  • Primitive versions: IntStream.iterate, LongStream.iterate and DoubleStream.iterate avoid boxing.
  • Overflow: int sequences wrap silently; use long or BigInteger for fast-growing sequences.
  • Seed is shared: if the seed is a mutable object, next should return a new one, as the Fibonacci example does.