In this guide, you will learn about the Stream iterate() method in Java programming and how to use it with an example.
1. Stream iterate() Method Overview
Definition:
The iterate() method in the Stream class is a static method used to create a sequential ordered Stream produced by iterative application of a function to an initial element. Each subsequent element is generated by applying the function to the previous element. There are two overloaded versions of this method: one introduced in Java 8 and another in Java 9.
Syntax:
1. static <T> Stream<T> iterate(T seed, UnaryOperator<T> f) // Java 8
2. static <T> Stream<T> iterate(T seed, Predicate<T> hasNext, UnaryOperator<T> f) // Java 9
Parameters:
- seed: the initial element.
- hasNext: a predicate to apply to elements to determine when the iteration should terminate.
- f: a function to be applied to the previous element to produce a new element.
Key Points:
- Used to create an infinite ordered Stream (Java 8) or a finite ordered Stream (Java 9) by iteratively applying a function.
- The seed parameter represents the first element in the Stream.
- The hasNext predicate (Java 9) determines when the iteration should stop.
- The f function is applied to generate subsequent elements in the Stream.
2. Stream iterate() Method Example
import java.util.function.Predicate;
import java.util.stream.Stream;
public class IterateExample {
public static void main(String[] args) {
// Java 8: Creating an infinite Stream, limit is used to limit the size of the stream
Stream<Integer> infiniteStream = Stream.iterate(1, n -> n + 1).limit(5);
System.out.println("Infinite Stream with limit:");
infiniteStream.forEach(System.out::println);
// Java 9: Creating a finite Stream using a hasNext predicate
Predicate<Integer> predicate = n -> n <= 5;
Stream<Integer> finiteStream = Stream.iterate(1, predicate, n -> n + 1);
System.out.println("Finite Stream:");
finiteStream.forEach(System.out::println);
}
}
Output:
Infinite Stream with limit: 1 2 3 4 5 Finite Stream: 1 2 3 4 5
Explanation:
In this example, we have demonstrated both overloads of the Stream::iterate() method.
1. In the first part, we used the Java 8 version of iterate(), creating an infinite Stream starting from 1 and incrementing each subsequent element by 1. We then used the limit() operation to limit the size of the Stream to 5 elements and printed these elements.
2. In the second part, we used the Java 9 version of iterate(), which takes an additional hasNext predicate. We defined a predicate that evaluates to true for values less than or equal to 5, making this a finite Stream. Then, we printed the elements of the finite Stream, which are the same as in the previous example.
Comments
Post a Comment
Leave Comment