Java 8 Stream.iterate examples

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

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


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

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

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

16

References

  1. Oracle doc – Java Stream Iterate

上一篇: Java Fibonacci examples
下一篇: Git How to undo the last commit?
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号