Domanda

Why guava's Iterables.filter wants superclass in predicate?

public static <T> Iterable<T> filter(final Iterable<T> unfiltered, final Predicate<? super T> predicate)

Could you show me how I can filter objects of custom class ? I tried this

I tried this

Iterator<TaskSchedule> it = tsp.getAllItems(getCustomerId(), "getId", filter);

com.google.common.collect.Iterables.filter(it, new Predicate<Object>() {
    @Override
    public boolean apply(Object input)
    {
        return false;
    }
});

which fails with following compilation error. I'm confused.

Error:(132, 44) java: C:\work\sideprojects\zzzz\SVN\inlineschedule-feature\test\cucumber\java\zzzz\com\zzz\cucumber\DBTestDriver.java:132: cannot find symbol symbol : method filter(java.util.Iterator,>) location: class com.google.common.collect.Iterables

I'm using JDK6

È stato utile?

Soluzione

Your compilation error is due to the fact that you're passing an Iterator to Iterables.filter, which expects an Iterable as its first argument. You want Iterators.filter.

It's unrelated to your actual problem, but since you asked: Iterables.filter takes a Predicate<? super T> so that you can, for example, use a Predicate<Object> to filter a List<String>. If the predicate can handle some supertype of the type you want to filter, you can use that predicate.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top