In fact, with Java 8, there is no need for any of that, because the required behavior is already built into the lazy execution model of streams. Iterators and generators are part and parcel of the Stream API.
The following code, for example, will print the infinite series of positive numbers:
Stream.iterate(1, x->x+1).forEach(System.out::println);Throwing in a limit(5) will give you the one-to-five example.
The reason that this works is that each stream element is only generated (lazily) when a downstream method explicitly asks for it. Contrary to appearances, no list of five elements is ever constructed in the snippet
Stream.iterate(1, x->x+1).limit(5).forEach(System.out::println);
To my eyes, the Java 8 code is even nicer to read than the corresponding code in C#.
No comments:
Post a Comment