Learnitweb

Stream iterate method in Java

1. Introduction

There are two overloaded versions of iterate method:

1. static <T> Stream<T> iterate​(T seed, UnaryOperator<T> f) : This was available in Java 8. This method takes an initial value and a function that provides next value. This method returns an infinite sequential ordered Stream produced by iterative application of a function f to an initial element seed.

Example

import java.util.stream.Stream;

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

    Output

    1
    2
    3
    4
    5

    2. static <T> Stream<T> iterate​(T seed, Predicate<? super T> hasNext, UnaryOperator<T> next) :

    The problem with two argument iterate method is that is returns an infinite Stream and we have to use limit method. To prevent infinite loops, in Java 9, another version of iterate method was introduced, which is a 3 argument method. The third argument is a predicate. The stream terminates as soon as the predicate returns false.

    Example

    import java.util.stream.Stream;
    
    public class IterateExample {
        public static void main(String[] args) {
            Stream.iterate(1, x -> x < 5, x -> x + 1).forEach(System.out::println);
        }
    }

    Output

    1
    2
    3
    4

    2. Conclusion

    In conclusion, the Stream.iterate() method in Java offers a powerful and flexible way to generate streams of elements based on iterative operations. By providing an initial seed value and a function to generate subsequent elements, it enables concise and efficient stream creation for various use cases. However, it’s crucial to use this method judiciously, considering factors such as performance implications and potential infinite streams. With proper understanding and usage, Stream.iterate() enriches the Java stream API, empowering developers to tackle complex data processing tasks with elegance and ease.