Google Collections (Guava Libraries): ImmutableSet / List / Map and Filtering

Suppose you want to create a copy of the ImmutableSet / List / Map object, but filter out some of the source records. One way to implement this:

 ImmutableList.copyOf(Iterables.filter(myObject, myObject.EQUALS)); 

where myObject.EQUALS is the predicate for the Iterables.filter() operation. I think this is a pretty elegant and readable implementation. However, one builds two list objects (first through a call to Iterables.filter(...) , the second through ImmutableList.copyOf(...) ), which is very inefficient.

Does anyone know a more efficient way to do this?

I think it would be best to add filter predicates to the ImmutableSet / List / Map constructors so that the object is created only once. But, unfortunately, there is no such parameter.

+6
java performance immutability guava
May 30 '11 at 13:29
source share
2 answers

The result of Iterables.filter() is just a view by the data in myObject : a new list is created only by ImmutableList.copyOf() using the filter iterator provided by Iterable

+16
May 30 '11 at 13:40
source share

Take a look at Guava Iterators

In particular, a filter (Iterator unfiltered, predicate predicate)

0
May 30 '11 at 13:40
source share



All Articles