Exemples Java 8 Stream.iterate
Dans Java 8, nous pouvons utiliserStream.iterate
pour créer des valeurs de flux à la demande, ce que l'on appelle un flux infini.
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));
Sortie
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));
Sortie
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));
Sortie
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.mapToInt(n -> n) .sum(); System.out.println("Fibonacci 10 sum : " + sum);
Sortie
Fibonacci 10 sum : 88
2. Java 9
Lestream.iterate
a été amélioré dans Java 9. Il prend en charge un prédicat (condition) comme deuxième argument, et lesstream.iterate
s'arrêteront si le prédicat est faux.
2.1 Stop the stream iteration if n >= 20
Stream.iterate(1, n -> n < 20 , n -> n * 2) .forEach(x -> System.out.println(x));
Sortie
1 2 4 8 16