简体   繁体   中英

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.

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, eg :

public static boolean allLessThan(Collection<Integer> numbers, Integer value) {
   for (Integer each : numbers) {
      if (each >= value) {
         return false;
      }
   }
   return true;
}

In short, differences between Predicates are:

  • apache-commons : is not generic;
  • guava : is generic;
  • javax.sql.rowset : is for use with RowSet s (for filtering SQL request results).

I believe that you want Comparable not Predicate .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM