Generator (computer programming): Difference between revisions

Content deleted Content added
m Icon: syntaxhighlight
Jmbeach1 (talk | contribs)
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">
public Iterable<Integer> fibonacci(intmyIterable = limit){Stream
IntStream.generate(new IntSupplier() {
int a = 1, b// =Generates 2;Fib sequence
.iterate(new Integer[]{ 1, 1 }, x -> new Integer[] { x[1], x[0] + x[1] })
 
.map(x -> x[0])::iterator;
public int getAsInt() {
})myIterable.forEach(System.out::println);
int temp = a;
a = b;
b = a + temp;
return temp;
}
}).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
return IntStream.generate(new IntSupplier() {
int// aGenerates =Fib 1, b = 2;sequence
.iterate(new Integer[]{ 1, 1 }, x -> new Integer[] { x[1], x[0] + x[1] })
.map(x -> x[0]).iterator();
 
// Print the first 5 elements
public int getAsInt() {
for (int i = 0; i < 5; i++) int temp = a;{
System.out.println(fmyGenerator.next());
a = b;
b = a + temp;
return temp;
}
}).limit(limit).boxed()::iterator;
}
 
System.out.println("done with first iteration");
// this could then be used as...
 
for (int f: fibonacci(10)) {
// Print the next 5 elements
System.out.println(f);
for (int f:i fibonacci(10)= 0; i < 5; i++) {
System.out.println(myGenerator.next());
}
 
/* Output:
1
1
2
3
5
done with first iteration
8
13
21
34
55 */
</syntaxhighlight>