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 get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024