Captain Man
Captain Man

Reputation: 7695

Guava predicate to filter various conditions without anonymous class or extra classes

With Java 6 and Guava 12.0 I am trying to filter a list of Strings based on if they have a specific prefix or not. Is there a way to do this without using anonymous classes or a separate class for each distinct prefix I want?

This works but it's ugly (even uglier with my company's imposed formatting I've removed).

private String foo(String prefix, List<String> stuff) {

    Collection<String> withPrefix = Collections2.filter(stuff, new Predicate<String>() {
        @Override
        public boolean apply(String input) {
            return input.startsWith(prefix);
        }
    });
    //...
}

Of course I could do something like the following.

public class PrefixCheckForAA implements Predicate<String> {

    @Override
    public boolean apply(String input) {
        return input.startsWith("AA");
    }
}

public class PrefixCheckForZZ implements Predicate<String> {

    @Override
    public boolean apply(String input) {
        return input.startsWith("ZZ");
    }
}

Is there any way to do this without anonymous classes or a bunch of seemingly redundant classes?

Upvotes: 1

Views: 657

Answers (2)

Fritz Duchardt
Fritz Duchardt

Reputation: 11870

While your own solution is perfectly valid, you can slim down your code even further by using Guava library functionality:

Collection<String> withPrefix = Collections2.filter(stuff, Predicates.containsPattern("^AA"));

For a list of all functionality of Predicates, please go here.

Upvotes: 3

Captain Man
Captain Man

Reputation: 7695

I found a solution while writing this, I can't believe I was so silly to not think of this...

Simply make the class have a constructor that requires a String, use this String as the prefix to check for.

public class PrefixChecker implements Predicate<String> {

    private final String prefix;

    public Prefix(String prefix) {
        this.prefix = prefix;
    }

    @Override
    public boolean apply(String input) {
        return input.startsWith(prefix);
    }
}

Upvotes: 4

Related Questions