8

Assume that you want to build a copy of an ImmutableSet/List/Map object but filter out some of the original entries. One way to implement that is the following:

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

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

Does anybody know of a more efficient way to do it?

I guess the best thing would be to add filter predicates to the ImmutableSet/List/Map builders so that the object must be constructed only once. But unfortunately there is no such parameter.

1
  • 1
    Perhaps you can use Predicates.equalTo() instead of implementing it :)
    – sly7_7
    Commented Jun 9, 2011 at 14:50

2 Answers 2

18

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

2
  • 6
    +1: this is little-known and frequently over-looked: filter() does not create a copy (with all the related advantages and disadvantages), it's just a view. Commented May 30, 2011 at 13:41
  • 1
    This is the same thing for Iterables.transform()
    – sly7_7
    Commented Jun 9, 2011 at 14:51
0

Look at Guava's Iterators

Specifically filter(Iterator unfiltered, Predicate predicate)

2
  • 1
    Well yes, that's used internally by Iterables.filter() :-) Commented May 30, 2011 at 14:17
  • Yep. You are right. Just looked at it. If in doubt I use always use the iterators but that is good to know (View).
    – Adam Gent
    Commented May 30, 2011 at 15:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.