I love using Guava’s Iterables filters. But one common code snippet looks like:
List foo = Lists.newArrayList(Iterables.filter(someCollection, somePredicate));
if (foo.isEmpty) {
// do empty
} else {
int count = foo.size(); // do non-empty
}
This is wasteful, as I don’t really need to build the “foo” list ever, all I need is to know if its empty or not and get a count of the number of elements.
I’d like to know the best practices for:
1) how do I test for isEmpty() without wasting time building the list into memory
2) Is there a way to get the size without iterating through all of the entries?
3) if there is no non-iterating solution to #2, is it better to just iterate and do count++?
FluentIterable.from(foo).filter(predicate).isEmpty()doesn’t iterate any more than it has to.But if you need the size, then you really want to use
FluentIterable.from(foo).filter(predicate).size(), which won’t store the elements but will just count up the ones that match the predicate.