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
- IntStream and LongStream
- Range and Aggregate Operations
- Mapping to and from Object Streams
- Generating Primitive Streams