views:

204

answers:

1

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);
+13  A: 

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().

Jon Skeet
Helpful Definitions: http://en.wikipedia.org/wiki/Lazy_evaluation.
S.Lott
thx for both the responses...also does google-collect use applicative or delayed evaluation
Pangea
i understood the laziness in filter and other methods as they return Iterable...but how can be explain the laziness w.r.t find and getOnlyElement
Pangea
@Pangea: I suspect those shouldn't be documented as being lazy.
Jon Skeet
But those methods *are* lazy! They do no work until they absolutely have to. It just happens to be right away that they have to. :)
Kevin Bourrillion