How are lazy streams implemented in Java 8?

前端 未结 3 635
我寻月下人不归
我寻月下人不归 2020-12-25 14:05

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

3条回答
  •  Happy的楠姐
    2020-12-25 14:27

    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 iter;
        private Predicate pred;
    
        public FilterIterable(Iterable iter, Predicate pred) {
            this.iter = iter;
            this.pred = pred;
        }
    
        public Iterator iterator() {
            return FilterIterator();
        }
    
        class FilterIterator implements Iterator
        {
            private Iterator 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.

提交回复
热议问题