Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guava: Iterables.filter VS Collections2.filter, any big difference?

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 Collections.

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?

like image 837
Sebastien Lorber Avatar asked May 31 '12 13:05

Sebastien Lorber


1 Answers

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.

like image 150
Louis Wasserman Avatar answered Nov 15 '22 16:11

Louis Wasserman