iterate java_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

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

.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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值