Guava: Iterables.frequency(Iterable<T>, Predicate<T>)
Is there really no method that determines the number of elements that satisfy a Predicate in an Iterable? Was I right to do this:
return Lists.newArrayList(Iterab开发者_运维问答les.filter(iterable, predicate)).size()
If so, what is the reason that there is no method
Iterable.frequency(Iterable<T>, Predicate<T>)
Cheers
This may be easier:
return Iterables.size(Iterables.filter(iterable, predicate));
It avoids the allocation of all that array memory.
When the iterable is a collection, you could say
return Collections2.filter(collection, predicate).size();
There hasn't been much demand for an Iterable.frequency(iterable, predicate) method.
This filter method does not create a collection. It creates a new Iterable with a new iterator and the filtering is done on demand
, like when you actually iterate over the Iterable.
So yes, the guava framework could have a frequency(Iterable, Predicate)
method, but this method would have to create the iterator internally just to get the number of iteration steps. And throw it away afterwards. And if your iterator works on dynamic collections (like database tables), the frequency "size" and the filter "size" may even be different.
If you need both (iterator and size), take the iterable, feed it in a suitable collection (freeze) and use the collections size()
method. This guarantees a true size value for the (frozen) collection based on the filtered Iterable.
精彩评论