Java 8 Stream.iterate examples

In Java 8, we can use Stream.iterate to create stream values on demand, so called infinite stream.

1. Stream.iterate

1.1 Stream of 0 – 9


	//Stream.iterate(initial value, next value)
	Stream.iterate(0, n -> n + 1)
                .limit(10)
                .forEach(x -> System.out.println(x));

Output


0
1
2
3
4
5
6
7
8
9

1.2 Stream of odd numbers only.


	Stream.iterate(0, n -> n + 1)
			.filter(x -> x % 2 != 0) //odd
			.limit(10)
			.forEach(x -> System.out.println(x));

Output


1
3
5
7
9
11
13
15
17
19

1.3 A classic Fibonacci example.


	Stream.iterate(new int[]{0, 1}, n -> new int[]{n[1], n[0] + n[1]})
		.limit(20)
		.map(n -> n[0])
		.forEach(x -> System.out.println(x));

Output


0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181

1.4 Sum all the Fibonacci values.


	int sum = Stream.iterate(new int[]{0, 1}, n -> new int[]{n[1], n[0] + n[1]})
                .limit(10)
                .map(n -> n[0]) // Stream<Integer>
                .mapToInt(n -> n)
                .sum();

        System.out.println("Fibonacci 10 sum : " + sum);

Output


Fibonacci 10 sum : 88

2. Java 9

The stream.iterate was enhanced in Java 9. It supports a predicate (condition) as second argument, and the stream.iterate will stop if the predicate is false.

2.1 Stop the stream iteration if n >= 20


	Stream.iterate(1, n -> n < 20 , n -> n * 2)
           .forEach(x -> System.out.println(x));

Output


1
2
4
8
16

References

  1. Oracle doc – Java Stream Iterate

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
basic Recent comment authors
newest oldest most voted
basic
Guest
basic

Nice, specially the Fibonacci series :)