I have a collection of Predicates, say List<Predicate<File>>. I then have a single File and I need to get the predicate (if any) that matches the file. I was thinking along the lines of using Iterables.find() but of course that takes a Predicate not a value to pass into a Predicate. I thought about implementing the following but don’t know if there already exists a mechanism.
public static <T> Predicate<Predicate<? super T>> createInversePredicate(
final T value) {
return new Predicate<Predicate<? super T>>() {
@Override
public boolean apply(Predicate<? super T> input) {
return input.apply(value);
}
};
}
This would allow me to do the following:
private List<Predicate<File>> filters = ...;
@Nullable
Predicate<File> findMatching(File file){
return Iterables.find(filters, createInversePredicate(file), null);
}
Is there a better way?
Guava team member here.
This is how I’d do it. There isn’t a better way.