Search code examples
javaguava

Using Predicate in Java for Comparison


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.


Solution

  • 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;
    }