Content deleted Content added
m →Icon: syntaxhighlight |
More useful/compact Java 8 generator examples |
||
Line 404:
Also an infinite Fibonacci sequence could also be written using '''Java 8''' Stream interface:
<syntaxhighlight lang="java">
.iterate(new Integer[]{ 1, 1 }, x -> new Integer[] { x[1], x[0] + x[1] })
.map(x -> x[0])::iterator;
▲}).forEach(System.out::println);
</syntaxhighlight>
Or get an Iterator from the '''Java 8''' super-interface BaseStream of Stream interface.
<syntaxhighlight lang="java">
// Save the iterator of a stream that generates fib sequence
▲public Iterable<Integer> fibonacci(int limit){
Iterator<Integer> myGenerator = Stream
.iterate(new Integer[]{ 1, 1 }, x -> new Integer[] { x[1], x[0] + x[1] })
.map(x -> x[0]).iterator();
// Print the first 5 elements
for (int i = 0; i < 5; i++)
}
System.out.println("done with first iteration");
for (int f: fibonacci(10)) {▼
// Print the next 5 elements
▲ System.out.println(f);
System.out.println(myGenerator.next());
}
/* Output:
1
1
2
3
5
done with first iteration
8
13
21
34
55 */
</syntaxhighlight>
|