Stream iterate(T seed, UnaryOperator f) example
Description
Stream iterate(T seed, UnaryOperator<T> f)
creates an infinite Stream from iterative application of a function f to an initial element seed.
The result Stream consists seed, f(seed), f(f(seed)), etc.
Syntax
iterate
has the following syntax.
static <T> Stream<T> iterate(T seed, UnaryOperator<T> f)
Example
The following example shows how to use iterate
.
import java.util.stream.Stream;
/*from w w w . j av a 2 s . co m*/
public class Main {
public static void main(String[] args) {
Stream.iterate(1,n->n + 1)
.limit(10)
.forEach(System.out::println);
}
}
The code above generates the following result.
Example 2
Calculate fibonnaci with iterate and Stream
import java.util.stream.Stream;
/*w w w . java 2 s.c o m*/
public class Main {
public static void main(String[] args) {
// fibonnaci with iterate
Stream.iterate(new int[]{0, 1}, t -> new int[]{t[1],t[0] + t[1]})
.limit(10)
.forEach(t -> System.out.println("(" + t[0] + ", " + t[1] + ")"));
}
}
The code above generates the following result.