Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass an extra (second) argument to Guava Predicate

Tags:

java

guava

I've got this Predicate, which filters my Task objects based in a date:

Predicate<Task> startDateFiltering = new Predicate<Task>() {
    @Override
    public boolean apply(Task input) {
        return input.getStartDate() != null
                && input.getStartDate().after(date);
    }

};

There's no problem to use it as long as date variable is accessible in the context. However, I'll like to make it reusable and embed it in the Task class itself, doing something like this:

public static final Predicate<Task> startDateFiltering = new Predicate<Task>() {
    @Override
    public boolean apply(Task input) {
        return input.getStartDate() != null
                && input.getStartDate().after(date);
    }

};

In order to access it as Task.startDateFiltering each time I need it. But how to pass the date argument to it?

like image 816
Xtreme Biker Avatar asked Sep 24 '14 15:09

Xtreme Biker


1 Answers

I'd create a static factory method (or just directly a new instance every time)

public static Predicate<Task> startDateFilteringWithDate(final Date date) {
    return new Predicate<Task>() {
        @Override
        public boolean apply(Task input) {
            return input.getStartDate() != null
                && input.getStartDate().after(date);
        }
    };
}
like image 179
Sotirios Delimanolis Avatar answered Sep 30 '22 17:09

Sotirios Delimanolis