Video in progress

Strong Middle 🌊 Streams and lambdas

How do Stream.iterate() and Stream.generate() differ, and what do they return with limit() in parallel mode?

iterate computes each element from the previous one and gives an ordered stream. generate takes from an independent Supplier and gives an unordered stream. That's why a parallel generate().limit(n) returns any n elements, not "the first n", and the supplier may be called more than n times.

📖 Answer

Stream.iterate(1, x -> x * 2).limit(5).toList();      // [1, 2, 4, 8, 16], always this
Stream.iterate(1, x -> x <= 100, x -> x * 3).toList(); // Java 9+: [1, 3, 9, 27, 81]

AtomicInteger counter = new AtomicInteger();
Stream.generate(counter::incrementAndGet).limit(5).toList();   // sequential: [1, 2, 3, 4, 5]

Now parallel:

AtomicInteger counter = new AtomicInteger();
List<Integer> ids = Stream.generate(counter::incrementAndGet)
        .parallel()
        .limit(5)
        .toList();
// for example [1, 3, 4, 7, 2] and counter.get() == 12

The generate Javadoc describes it as an "infinite sequential unordered stream". There's no order, so limit can take any 5. Workers request in batches ahead of time, so the supplier is called extra times: if it hands out consecutive numbers (an ID, a ticket number), numbers get "lost".

iterate gives the correct result in parallel, but inefficiently: each element depends on the previous one, so it can't be split, and the parallel version is often slower.

The rule:

  • you need consecutive numbers: IntStream.range / rangeClosed (splits well, no boxing);
  • a stateful sequence (each from the previous): iterate, in sequential mode;
  • independent values (a random number, a UUID): generate.

Passing a stateful supplier (a counter) to generate is a signal in itself: what you actually need is iterate or range.