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.

How do I use for-each in Java?

Using for-each command to iterate arrays or a list can simplified our code. Below is an example how to do it in Java. The first loop is for iterating array and the second for iterating a list containing a some names.

package org.kodejava.lang;

import java.util.ArrayList;
import java.util.List;

public class ForEachExample {
    public static void main(String[] args) {
        Integer[] numbers = {10, 100, 1000, 10000, 100000, 1000000};

        for (Integer i : numbers) {
            System.out.println("Number: " + i);
        }

        List<String> names = new ArrayList<>();
        names.add("Musk");
        names.add("Nakamoto");
        names.add("Einstein");

        for (String name : names) {
            System.out.println("Name: " + name);
        }
    }
}

The result of the code snippet:

Number: 10
Number: 100
Number: 1000
Number: 10000
Number: 100000
Number: 1000000
Name: Musk
Name: Nakamoto
Name: Einstein