I'd like to know in Guava if there are any differences between the Iterables.filter(Iterable, Predicate)
and Collections2.filter(Collection, Predicate)
methods?
They seem to both maintain the iteration order, and to provide a live view.
Javadoc says calling Collections2.filter().size()
will iterate over all elements.
Suppose I have a predicate to filter a list of items, and as a result I want the number of items left in the view (or the list, doesn't matter). What am I supposed to use?
It seems simpler to use Collections2.filter
as the size()
method is provided by Collection
s.
But in the background, is there a difference between:
ImmutableList.copyOf(
Iterables.filter(lead.getActions(), isRealActionDoneByUserPredicate)
).size();
And:
Collections2.filter(lead.getActions(),isRealActionDoneByUserPredicate).size();
By the way, is building an ImmutableList
faster than building a normal ArrayList
?
Guava contributor here.
Collections2.filter(elements, predicate).size()
is preferable, as it does no copying -- both filter
methods return a view -- but
Iterables.size(Iterables.filter(elements, predicate))
is essentially equivalent, and will similarly find the answer without any copying.
As for the relative speed of constructing an ArrayList
versus an ImmutableList
, it varies by which construction method you use:
ImmutableList.copyOf(collection)
should take almost exactly the same amount of time. (It has to check for nulls, but that's cheap.)ImmutableList.builder()....build()
takes a small constant factor longer, because it has to use an ArrayList
inside the Builder
, since we don't know in advance how many elements will be added.ImmutableList.of(...)
will have about equal speed.That said, the conceptual benefits of using ImmutableList
often outweigh the small performance costs, especially if you'll be passing the lists around frequently.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With