If you want your method to accept as many different types of collections as possible, and you want to be sure that the result is the same type of implementation as you, you can use the void
method, which directly modifies the supplied collection. For instance:
import com.google.common.base.Predicate; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; public class Testy { private static <T> void filter(Iterable<T> collection, Predicate<T> filter) { Iterator<T> iterator = collection.iterator(); while (iterator.hasNext()) { if (!filter.apply(iterator.next())) {
The filter
helper method accepts Iterable
, the simplest type needed to iterate over something. Apply a filter to each element, and if the predicate (filter) returns false, remove this element from the base collection using Iterator.remove()
.
The Predicate<T>
interface here comes from Google. You can easily write your own if you do not want to import it. The only method required is apply(T)
, which returns a boolean value. Either this, or just write your condition directly inside the loop and get rid of the second parameter.
This method is most effective if your source collection is volatile and you do not want to keep intermediate results.
Another option is to use Google Collections Collections2.filter(Collection<E>, Predicate<E>)
, which returns Collection<E>
, as in your question. Similarly, the Iterables
class will do the same, but create lazy iterations where filters are applied only when the iteration is actually performed.
source share