Question

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);
Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top