Find matching Predicate. Predicate of Predicate?

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>>() {

        public boolean apply(Predicate<? super T> input) {
            return input.apply(value);

This would allow me to do the following:

private List<Predicate<File>> filters = ...;

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.

I would avoid the complexity of creating an "inverse" predicate, and simply use imperative code:

private List<Predicate<File>> filters = ...;

Predicate<File> findMatchingFilter(File file){
    for (Predicate<File> filter : filters) {
        if (filter.apply(file)) {
            return filter;
    return null;

It's more straightforward, and the next programmer won't need to take 1 minute to understand this "inverse" predicate business :)

Java 8 users can do this:

Predicate<File> findMatching(File file) {
  List<Predicate<File>> matchingFilters = -> predicate.test(file)).collect(Collectors.toList());
  return matchingFilters.isEmpty()? null : matchingFilters.get(0);

Here I am assuming only one predicate will match the file.

You can also use Optional<Predicate<File>> instead of @Nullable in Java 8.

Need Your Help

RScript: how to get the plots saved into multiple files (say png) rather than saved into the Rplots.pdf?

r plot rscript

I use RScript in Windows and by default it saves the plots into the pdf file Rplots.pdf, one plot per page.

How can I create a local user profile for the anonymous user of an ASP.Net MVC application under IIS 7? iis-7 windows-7 forms-authentication sql-server-express

I've been experimenting with ASP.Net MVC, and have come across a problem that is probably not specifically MVC related. But I cannot get the authentication in the default MVC application (the one c...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.