I could use new List(Collection2.filter()) , of course, but in this way it did not guarantee that my order would remain the same.
This is not true. Collections2.filter() is a lazily evaluated function - it does not actually filter your collection until you start accessing the filtered version. For example, if you iterate over a filtered version, then the filtered items will exit the iterator in the same order as the original collection (except for those that were filtered, obviously).
You may have thought that it performs filtering in front, and then uploads the results to an arbitrary disordered collection of some form - this is not so.
So, if you use the output of Collections2.filter() as an input to a new list, then your original order will be saved.
Using static imports (and the Lists.newArrayList function), it gets pretty concise:
List filteredList = newArrayList(filter(originalList, predicate));
Please note that until Collections2.filter eagerly Lists.newArrayList over the base collection, Lists.newArrayList will - it will extract all the elements of the filtered collection and copy them to the new ArrayList .
skaffman Dec 10 '11 at 20:32 2011-12-10 20:32
source share