How do I use Stream.iterate() method?

The Stream.iterate() method in Java is used to generate a Stream of elements based on some iterative logic.

The simplest form Stream.iterate(initialValue, lambdaFunction) takes in an initial value and a UnaryOperator function to compute the next element in the series.

Here’s an example of using `Stream.iterate()“ to create a Stream of incremental numbers:

package org.kodejava.util;

import java.util.stream.Stream;

public class StreamIterate {
    public static void main(String[] args) {
        Stream<Integer> stream = Stream.iterate(0, n -> n + 1);
        stream
                .limit(10)
                .forEach(System.out::println);
    }
}

In this example, Stream.iterate(0, n -> n + 1) creates an infinite Stream starting from 0, where each next element is calculated by adding 1 to the previous element (n -> n + 1). The stream is then limited to the first 10 elements, and each of those elements is printed to the console.

Since Java 9, Stream.iterate() also has an overloaded method Stream.iterate(initialValue, predicate, function) which also takes a Predicate to specify the condition when to stop iteration.

For example:

package org.kodejava.util;

import java.util.stream.Stream;

public class StreamIterateExample {
    public static void main(String[] args) {
        Stream<Integer> stream = Stream.iterate(0, n -> n <= 10, n -> n + 1);
        stream.forEach(System.out::println);
    }
}

In this example, Stream.iterate(0, n -> n <= 10 , n -> n + 1) creates a Stream starting from 0, and ends when the value exceeds 10. Each next element is calculated by adding 1 to the previous element (n -> n + 1). Each of those elements is then printed to the console.

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.