Java – pass additional (second) parameters to guava predicate
•
Java
I have this predicate to filter my task objects by date:
Predicate<Task> startDateFiltering = new Predicate<Task>() { @Override public boolean apply(Task input) { return input.getStartDate() != null && input.getStartDate().after(date); } };
As long as the date variable can be accessed in context, there is no problem using it However, I want to make it reusable and embed it in the task class itself by doing the following:
public static final Predicate<Task> startDateFiltering = new Predicate<Task>() { @Override public boolean apply(Task input) { return input.getStartDate() != null && input.getStartDate().after(date); } };
To make it a task every time you need it Startdatefiltering access But how do you pass the date parameter to it?
Solution
I created a static factory method (or just create a new instance each 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); } }; }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码