0Pricing
Java Academy · Lesson

Generating Primitive Streams

iterate and generate.

Infinite Streams Need Limits

iterate and generate create potentially infinite streams. You must add limit (or a predicate) to make them finite.

import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) {
        IntStream.iterate(1, n -> n + 1)
            .limit(5)
            .forEach(System.out::println);
    }
}

iterate with a Seed

iterate(seed, next) starts at the seed and repeatedly applies the function to the previous value.

import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) {
        IntStream.iterate(2, n -> n * 2)
            .limit(5)
            .forEach(System.out::println);
    }
}

All lessons in this course

  1. IntStream and LongStream
  2. Range and Aggregate Operations
  3. Mapping to and from Object Streams
  4. Generating Primitive Streams
← Back to Java Academy