I am reading Java 8, specifically the \"Streams API\". I wanted to know how streams can be lazy?
I believe streams are just added as a library and there are no chang
streaming is not a container of data, but a container of logic. you just need to pass in an instance of interface to remember the logic.
consider following code:
class FilterIterable implements Iterable
{
private Iterable extends T> iter;
private Predicate super T> pred;
public FilterIterable(Iterable extends T> iter, Predicate super T> pred) {
this.iter = iter;
this.pred = pred;
}
public Iterator iterator() {
return FilterIterator();
}
class FilterIterator implements Iterator
{
private Iterator extends T> iterator = iter.iterator();
private T next = null;
FilterIterator() {
getNext();
}
private void getNext() {
next = null;
while (iterator.hasNext()) {
T temp = iterator.next();
if (pred.test(temp)) {
next = temp;
break;
}
}
}
public boolean hasNext() { return next != null; }
public T next() {
T temp = next;
getNext();
return temp;
}
}
}
the logic is wrapped inside of pred, but only invoked when the object gets iterated. and in fact, this class stores no data, it only keeps an iterable that may contain data, or even just another logic holder itself.
and elements are returned on demand too. this kind of paradigm makes so called stream api lazy.