Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most of the Iterators and Iterables methods are LAZY! What does this mean

Tags:

1 of the presentation says "These methods are LAZY!"

Iterable transform(Iterable, Function)* Iterable filter(Iterable, Predicate)* T find(Iterable<T>, Predicate) Iterable concat(Iterable<Iterable>) Iterable cycle(Iterable) T getOnlyElement(Iterable<T>) Iterable<T> reverse(List<T>) 

Can someone help me understand what they mean by this, lets say I've a collection of Persons and I apply a filter to return only the persons whose last name is DOE.

So does this mean that the "filtering happens only on the first call to doeOnly.next()?"

List<Person> persons= .... Iterable doeOnly= Iterables.filter(persons,DOE_AS_LAST_NAME_PREDICATE); 
like image 922
Aravind Yarram Avatar asked Jan 28 '10 15:01

Aravind Yarram


People also ask

Why are iterators considered lazy in JavaScript?

Iterators in JavaScript (since ECMAScript 6) are what make it possible to lazy evaluate and create user-defined data sequences. Iteration is a mechanism for traversing data. Iterators are pointers for traversing elements of data structure, called Iterable. A pointer for producing a sequence of values.

What is a lazy iterable in Python?

Laziness. An iterable is anything that you can iterate over. In other words, anything you can loop over with a for loop. Generators are iterables, but they're a little weird as iterables go. Generators are lazy.

What is a lazy iterator Java?

All Implemented Interfaces: Iterator<E> public abstract class LazyIteratorChain<E> extends Object implements Iterator<E> An LazyIteratorChain is an Iterator that wraps a number of Iterators in a lazy manner. This class makes multiple iterators look like one to the caller.

Are iterators lazy Python?

Iterators use the lazy evaluation approach. Many built-in classes in Python are iterators. A generator function is a function which returns an iterator. A generator expression is an expression that returns an iterator.


1 Answers

It means that the data is filtered as you request it - it doesn't go through your list immediately, and build up a new list of the filtered data. Instead, when you call iterator.next() (e.g. automatically in an enhanced for loop) the iterator will ask its upstream data source (your collection) for the next data item. It will then try to match this against the filter. If it matches it, it'll return that item. Otherwise, it'll ask for another item from the collection, keeping going until it either runs out of items or finds a match.

Then when you next ask for the next item, it'll keep going from where it left off.

In other words, it doesn't just mean "filtering happens only on the first call to doeOnly.next()" - it means "filtering happens on each call to iterator.next()" where iterator is the result of calling doeOnly.iterator().

like image 109
Jon Skeet Avatar answered Nov 22 '22 09:11

Jon Skeet