I have a method which is supposed to compare a value with a list of values.
The compare function can be less than, greater than or equal to. I came across this Predicate concept which I am trying to understand and implement in this case.
Below are my few questions.
1) There is Predicate class defined in apache commons, guava and javax.sql. What's the difference between them? (I tried going through docs but couldn't get it)
2) Is Guava predicate only meant to do filtering and not say a boolean function implementaion?
3) Can I get an example for the Predicate?
Thanks.
Assuming that you want to test whether all elements of a given collection satisfy some condition, this is an example with guava's Predicate (@ColinD's comment points to a wealth of already existing predicates involving Comparable!):
public static class LessThan<T extends Comparable<T>> implements Predicate<T> {
private final Comparable<T> value;
public LessThan(final Comparable<T> value) {
this.value = value;
}
@Override
public boolean apply(final T input) {
return value.compareTo(input) > 0;
}
}
public static void main(final String[] args) {
final Collection<Integer> things = Arrays.asList(1, 2, 3, 4);
System.out.println(Iterables.all(things, new LessThan<Integer>(5)));
}
But unless you can reuse that predicate, you should consider a non-functional version as the guava wiki suggests, e.g. :
public static boolean allLessThan(Collection<Integer> numbers, Integer value) {
for (Integer each : numbers) {
if (each >= value) {
return false;
}
}
return true;
}
I think Errandir got to the core of your problem: a predicate is a function from its input to a boolean, and you want to do tri-state comparison.
To answer your other questions though:
Is Guava predicate only meant to do filtering and not say a boolean function implementation?
No. A Guava predicate is a function that returns a boolean. You can phrase most problems that are solved by predicates in terms of some kind of filtering, but they can be used without any collection that is being filtered.
Can I get an example for the Predicate?
Here's a predicate that has uses independent of a collection:
Predicate<Person> isAuthorizedToBuyAlcohol = new Predicate<Person>() {
public boolean apply(Person person) {
return person.age() >= LEGAL_LIMIT;
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With