Home | History | Annotate | Download | only in base
      1 /*
      2  * Copyright (C) 2007 Google Inc.
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not
      5  * use this file except in compliance with the License. You may obtain a copy of
      6  * the License at
      7  *
      8  * http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
     12  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
     13  * License for the specific language governing permissions and limitations under
     14  * the License.
     15  */
     16 
     17 package com.google.common.base;
     18 
     19 import com.google.common.annotations.GwtCompatible;
     20 import com.google.common.annotations.GwtIncompatible;
     21 import static com.google.common.base.Preconditions.checkNotNull;
     22 
     23 import java.io.Serializable;
     24 import java.util.ArrayList;
     25 import java.util.Arrays;
     26 import java.util.Collection;
     27 import java.util.Iterator;
     28 import java.util.List;
     29 
     30 import javax.annotation.Nullable;
     31 
     32 /**
     33  * Contains static factory methods for creating {@code Predicate} instances.
     34  *
     35  * <p>All methods returns serializable predicates as long as they're given
     36  * serializable parameters.
     37  *
     38  * @author Kevin Bourrillion
     39  * @since 2010.01.04 <b>stable</b> (imported from Google Collections Library)
     40  */
     41 @GwtCompatible
     42 public final class Predicates {
     43   private Predicates() {}
     44 
     45   // TODO: considering having these implement a VisitablePredicate interface
     46   // which specifies an accept(PredicateVisitor) method.
     47 
     48   /**
     49    * Returns a predicate that always evaluates to {@code true}.
     50    */
     51   @GwtCompatible(serializable = true)
     52   @SuppressWarnings("unchecked")
     53   public static <T> Predicate<T> alwaysTrue() {
     54     return (Predicate<T>) AlwaysTruePredicate.INSTANCE;
     55   }
     56 
     57   /**
     58    * Returns a predicate that always evaluates to {@code false}.
     59    */
     60   @GwtCompatible(serializable = true)
     61   @SuppressWarnings("unchecked")
     62   public static <T> Predicate<T> alwaysFalse() {
     63     return (Predicate<T>) AlwaysFalsePredicate.INSTANCE;
     64   }
     65 
     66   /**
     67    * Returns a predicate that evaluates to {@code true} if the object reference
     68    * being tested is null.
     69    */
     70   @SuppressWarnings("unchecked")
     71   public static <T> Predicate<T> isNull() {
     72     return (Predicate<T>) IsNullPredicate.INSTANCE;
     73   }
     74 
     75   /**
     76    * Returns a predicate that evaluates to {@code true} if the object reference
     77    * being tested is not null.
     78    */
     79   @SuppressWarnings("unchecked")
     80   public static <T> Predicate<T> notNull() {
     81     return (Predicate<T>) NotNullPredicate.INSTANCE;
     82   }
     83 
     84   /**
     85    * Returns a predicate that evaluates to {@code true} if the given predicate
     86    * evaluates to {@code false}.
     87    */
     88   public static <T> Predicate<T> not(Predicate<T> predicate) {
     89     return new NotPredicate<T>(predicate);
     90   }
     91 
     92   /**
     93    * Returns a predicate that evaluates to {@code true} if each of its
     94    * components evaluates to {@code true}. The components are evaluated in
     95    * order, and evaluation will be "short-circuited" as soon as a false
     96    * predicate is found. It defensively copies the iterable passed in, so future
     97    * changes to it won't alter the behavior of this predicate. If {@code
     98    * components} is empty, the returned predicate will always evaluate to {@code
     99    * true}.
    100    */
    101   public static <T> Predicate<T> and(
    102       Iterable<? extends Predicate<? super T>> components) {
    103     return new AndPredicate<T>(defensiveCopy(components));
    104   }
    105 
    106   /**
    107    * Returns a predicate that evaluates to {@code true} if each of its
    108    * components evaluates to {@code true}. The components are evaluated in
    109    * order, and evaluation will be "short-circuited" as soon as a false
    110    * predicate is found. It defensively copies the array passed in, so future
    111    * changes to it won't alter the behavior of this predicate. If {@code
    112    * components} is empty, the returned predicate will always evaluate to {@code
    113    * true}.
    114    */
    115   public static <T> Predicate<T> and(Predicate<? super T>... components) {
    116     return new AndPredicate<T>(defensiveCopy(components));
    117   }
    118 
    119   /**
    120    * Returns a predicate that evaluates to {@code true} if both of its
    121    * components evaluate to {@code true}. The components are evaluated in
    122    * order, and evaluation will be "short-circuited" as soon as a false
    123    * predicate is found.
    124    */
    125   public static <T> Predicate<T> and(Predicate<? super T> first,
    126       Predicate<? super T> second) {
    127     return new AndPredicate<T>(Predicates.<T>asList(
    128         checkNotNull(first), checkNotNull(second)));
    129   }
    130 
    131   /**
    132    * Returns a predicate that evaluates to {@code true} if any one of its
    133    * components evaluates to {@code true}. The components are evaluated in
    134    * order, and evaluation will be "short-circuited" as soon as as soon as a
    135    * true predicate is found. It defensively copies the iterable passed in, so
    136    * future changes to it won't alter the behavior of this predicate. If {@code
    137    * components} is empty, the returned predicate will always evaluate to {@code
    138    * false}.
    139    */
    140   public static <T> Predicate<T> or(
    141       Iterable<? extends Predicate<? super T>> components) {
    142     return new OrPredicate<T>(defensiveCopy(components));
    143   }
    144 
    145   /**
    146    * Returns a predicate that evaluates to {@code true} if any one of its
    147    * components evaluates to {@code true}. The components are evaluated in
    148    * order, and evaluation will be "short-circuited" as soon as as soon as a
    149    * true predicate is found. It defensively copies the array passed in, so
    150    * future changes to it won't alter the behavior of this predicate. If {@code
    151    * components} is empty, the returned predicate will always evaluate to {@code
    152    * false}.
    153    */
    154   public static <T> Predicate<T> or(Predicate<? super T>... components) {
    155     return new OrPredicate<T>(defensiveCopy(components));
    156   }
    157 
    158   /**
    159    * Returns a predicate that evaluates to {@code true} if either of its
    160    * components evaluates to {@code true}. The components are evaluated in
    161    * order, and evaluation will be "short-circuited" as soon as as soon as a
    162    * true predicate is found.
    163    */
    164   public static <T> Predicate<T> or(Predicate<? super T> first,
    165       Predicate<? super T> second) {
    166     return new OrPredicate<T>(Predicates.<T>asList(
    167         checkNotNull(first), checkNotNull(second)));
    168   }
    169 
    170   /**
    171    * Returns a predicate that evaluates to {@code true} if the object being
    172    * tested {@code equals()} the given target or both are null.
    173    */
    174   public static <T> Predicate<T> equalTo(@Nullable T target) {
    175     // TODO: Change signature to return Predicate<Object>.
    176     return (target == null)
    177         ? Predicates.<T>isNull()
    178         : new IsEqualToPredicate<T>(target);
    179   }
    180 
    181   /**
    182    * Returns a predicate that evaluates to {@code true} if the object being
    183    * tested is an instance of the given class. If the object being tested
    184    * is {@code null} this predicate evaluates to {@code false}.
    185    *
    186    * <p>If you want to filter an {@code Iterable} to narrow its type, consider
    187    * using {@link com.google.common.collect.Iterables#filter(Iterable, Class)}
    188    * in preference.
    189    */
    190   @GwtIncompatible("Class.isInstance")
    191   public static Predicate<Object> instanceOf(Class<?> clazz) {
    192     return new InstanceOfPredicate(clazz);
    193   }
    194 
    195   /**
    196    * Returns a predicate that evaluates to {@code true} if the object reference
    197    * being tested is a member of the given collection. It does not defensively
    198    * copy the collection passed in, so future changes to it will alter the
    199    * behavior of the predicate.
    200    *
    201    * This method can technically accept any Collection<?>, but using a typed
    202    * collection helps prevent bugs. This approach doesn't block any potential
    203    * users since it is always possible to use {@code Predicates.<Object>in()}.
    204    *
    205    * @param target the collection that may contain the function input
    206    */
    207   public static <T> Predicate<T> in(Collection<? extends T> target) {
    208     return new InPredicate<T>(target);
    209   }
    210 
    211   /**
    212    * Returns the composition of a function and a predicate. For every {@code x},
    213    * the generated predicate returns {@code predicate(function(x))}.
    214    *
    215    * @return the composition of the provided function and predicate
    216    */
    217   public static <A, B> Predicate<A> compose(
    218       Predicate<B> predicate, Function<A, ? extends B> function) {
    219     return new CompositionPredicate<A, B>(predicate, function);
    220   }
    221 
    222   /** @see Predicates#alwaysTrue() */
    223   // Package private for GWT serialization.
    224   enum AlwaysTruePredicate implements Predicate<Object> {
    225     INSTANCE;
    226 
    227     public boolean apply(Object o) {
    228       return true;
    229     }
    230     @Override public String toString() {
    231       return "AlwaysTrue";
    232     }
    233   }
    234 
    235   /** @see Predicates#alwaysFalse() */
    236   // Package private for GWT serialization.
    237   enum AlwaysFalsePredicate implements Predicate<Object> {
    238     INSTANCE;
    239 
    240     public boolean apply(Object o) {
    241       return false;
    242     }
    243     @Override public String toString() {
    244       return "AlwaysFalse";
    245     }
    246   }
    247 
    248   /** @see Predicates#not(Predicate) */
    249   private static class NotPredicate<T>
    250       implements Predicate<T>, Serializable {
    251     private final Predicate<T> predicate;
    252 
    253     private NotPredicate(Predicate<T> predicate) {
    254       this.predicate = checkNotNull(predicate);
    255     }
    256     public boolean apply(T t) {
    257       return !predicate.apply(t);
    258     }
    259     @Override public int hashCode() {
    260       return ~predicate.hashCode(); /* Invert all bits. */
    261     }
    262     @Override public boolean equals(Object obj) {
    263       if (obj instanceof NotPredicate<?>) {
    264         NotPredicate<?> that = (NotPredicate<?>) obj;
    265         return predicate.equals(that.predicate);
    266       }
    267       return false;
    268     }
    269     @Override public String toString() {
    270       return "Not(" + predicate.toString() + ")";
    271     }
    272     private static final long serialVersionUID = 0;
    273   }
    274 
    275   private static final Joiner commaJoiner = Joiner.on(",");
    276 
    277   /** @see Predicates#and(Iterable) */
    278   private static class AndPredicate<T>
    279       implements Predicate<T>, Serializable {
    280     private final Iterable<? extends Predicate<? super T>> components;
    281 
    282     private AndPredicate(Iterable<? extends Predicate<? super T>> components) {
    283       this.components = components;
    284     }
    285     public boolean apply(T t) {
    286       for (Predicate<? super T> predicate : components) {
    287         if (!predicate.apply(t)) {
    288           return false;
    289         }
    290       }
    291       return true;
    292     }
    293     @Override public int hashCode() {
    294       int result = -1; /* Start with all bits on. */
    295       for (Predicate<? super T> predicate : components) {
    296         result &= predicate.hashCode();
    297       }
    298       return result;
    299     }
    300     @Override public boolean equals(Object obj) {
    301       if (obj instanceof AndPredicate<?>) {
    302         AndPredicate<?> that = (AndPredicate<?>) obj;
    303         return iterableElementsEqual(components, that.components);
    304       }
    305       return false;
    306     }
    307     @Override public String toString() {
    308       return "And(" + commaJoiner.join(components) + ")";
    309     }
    310     private static final long serialVersionUID = 0;
    311   }
    312 
    313   /** @see Predicates#or(Iterable) */
    314   private static class OrPredicate<T>
    315       implements Predicate<T>, Serializable {
    316     private final Iterable<? extends Predicate<? super T>> components;
    317 
    318     private OrPredicate(Iterable<? extends Predicate<? super T>> components) {
    319       this.components = components;
    320     }
    321     public boolean apply(T t) {
    322       for (Predicate<? super T> predicate : components) {
    323         if (predicate.apply(t)) {
    324           return true;
    325         }
    326       }
    327       return false;
    328     }
    329     @Override public int hashCode() {
    330       int result = 0; /* Start with all bits off. */
    331       for (Predicate<? super T> predicate : components) {
    332         result |= predicate.hashCode();
    333       }
    334       return result;
    335     }
    336     @Override public boolean equals(Object obj) {
    337       if (obj instanceof OrPredicate<?>) {
    338         OrPredicate<?> that = (OrPredicate<?>) obj;
    339         return iterableElementsEqual(components, that.components);
    340       }
    341       return false;
    342     }
    343     @Override public String toString() {
    344       return "Or(" + commaJoiner.join(components) + ")";
    345     }
    346     private static final long serialVersionUID = 0;
    347   }
    348 
    349   /** @see Predicates#equalTo(Object) */
    350   private static class IsEqualToPredicate<T>
    351       implements Predicate<T>, Serializable {
    352     private final T target;
    353 
    354     private IsEqualToPredicate(T target) {
    355       this.target = target;
    356     }
    357     public boolean apply(T t) {
    358       return target.equals(t);
    359     }
    360     @Override public int hashCode() {
    361       return target.hashCode();
    362     }
    363     @Override public boolean equals(Object obj) {
    364       if (obj instanceof IsEqualToPredicate) {
    365         IsEqualToPredicate<?> that = (IsEqualToPredicate<?>) obj;
    366         return target.equals(that.target);
    367       }
    368       return false;
    369     }
    370     @Override public String toString() {
    371       return "IsEqualTo(" + target + ")";
    372     }
    373     private static final long serialVersionUID = 0;
    374   }
    375 
    376   /** @see Predicates#instanceOf(Class) */
    377   private static class InstanceOfPredicate
    378       implements Predicate<Object>, Serializable {
    379     private final Class<?> clazz;
    380 
    381     private InstanceOfPredicate(Class<?> clazz) {
    382       this.clazz = checkNotNull(clazz);
    383     }
    384     public boolean apply(Object o) {
    385       return Platform.isInstance(clazz, o);
    386     }
    387     @Override public int hashCode() {
    388       return clazz.hashCode();
    389     }
    390     @Override public boolean equals(Object obj) {
    391       if (obj instanceof InstanceOfPredicate) {
    392         InstanceOfPredicate that = (InstanceOfPredicate) obj;
    393         return clazz == that.clazz;
    394       }
    395       return false;
    396     }
    397     @Override public String toString() {
    398       return "IsInstanceOf(" + clazz.getName() + ")";
    399     }
    400     private static final long serialVersionUID = 0;
    401   }
    402 
    403   /** @see Predicates#isNull() */
    404   // enum singleton pattern
    405   private enum IsNullPredicate implements Predicate<Object> {
    406     INSTANCE;
    407 
    408     public boolean apply(Object o) {
    409       return o == null;
    410     }
    411     @Override public String toString() {
    412       return "IsNull";
    413     }
    414   }
    415 
    416   /** @see Predicates#notNull() */
    417   // enum singleton pattern
    418   private enum NotNullPredicate implements Predicate<Object> {
    419     INSTANCE;
    420 
    421     public boolean apply(Object o) {
    422       return o != null;
    423     }
    424     @Override public String toString() {
    425       return "NotNull";
    426     }
    427   }
    428 
    429   /** @see Predicates#in(Collection) */
    430   private static class InPredicate<T>
    431       implements Predicate<T>, Serializable {
    432     private final Collection<?> target;
    433 
    434     private InPredicate(Collection<?> target) {
    435       this.target = checkNotNull(target);
    436     }
    437 
    438     public boolean apply(T t) {
    439       try {
    440         return target.contains(t);
    441       } catch (NullPointerException e) {
    442         return false;
    443       } catch (ClassCastException e) {
    444         return false;
    445       }
    446     }
    447 
    448     @Override public boolean equals(Object obj) {
    449       if (obj instanceof InPredicate<?>) {
    450         InPredicate<?> that = (InPredicate<?>) obj;
    451         return target.equals(that.target);
    452       }
    453       return false;
    454     }
    455 
    456     @Override public int hashCode() {
    457       return target.hashCode();
    458     }
    459 
    460     @Override public String toString() {
    461       return "In(" + target + ")";
    462     }
    463     private static final long serialVersionUID = 0;
    464   }
    465 
    466   /** @see Predicates#compose(Predicate, Function) */
    467   private static class CompositionPredicate<A, B>
    468       implements Predicate<A>, Serializable {
    469     final Predicate<B> p;
    470     final Function<A, ? extends B> f;
    471 
    472     private CompositionPredicate(Predicate<B> p, Function<A, ? extends B> f) {
    473       this.p = checkNotNull(p);
    474       this.f = checkNotNull(f);
    475     }
    476 
    477     public boolean apply(A a) {
    478       return p.apply(f.apply(a));
    479     }
    480 
    481     @Override public boolean equals(Object obj) {
    482       if (obj instanceof CompositionPredicate<?, ?>) {
    483         CompositionPredicate<?, ?> that = (CompositionPredicate<?, ?>) obj;
    484         return f.equals(that.f) && p.equals(that.p);
    485       }
    486       return false;
    487     }
    488 
    489     @Override public int hashCode() {
    490       /*
    491        * TODO:  To leave the door open for future enhancement, this
    492        * calculation should be coordinated with the hashCode() method of the
    493        * corresponding composition method in Functions.  To construct the
    494        * composition:
    495        *    predicate(function2(function1(x)))
    496        *
    497        * There are two different ways of composing it:
    498        *    compose(predicate, compose(function2, function1))
    499        *    compose(compose(predicate, function2), function1)
    500        *
    501        * It would be nice if these could be equal.
    502        */
    503       return f.hashCode() ^ p.hashCode();
    504     }
    505 
    506     @Override public String toString() {
    507       return p.toString() + "(" + f.toString() + ")";
    508     }
    509 
    510     private static final long serialVersionUID = 0;
    511   }
    512 
    513   /**
    514    * Determines whether the two Iterables contain equal elements. More
    515    * specifically, this method returns {@code true} if {@code iterable1} and
    516    * {@code iterable2} contain the same number of elements and every element of
    517    * {@code iterable1} is equal to the corresponding element of {@code
    518    * iterable2}.
    519    *
    520    * <p>This is not a general-purpose method; it assumes that the iterations
    521    * contain no {@code null} elements.
    522    */
    523   private static boolean iterableElementsEqual(
    524       Iterable<?> iterable1, Iterable<?> iterable2) {
    525     Iterator<?> iterator1 = iterable1.iterator();
    526     Iterator<?> iterator2 = iterable2.iterator();
    527     while (iterator1.hasNext()) {
    528       if (!iterator2.hasNext()) {
    529         return false;
    530       }
    531       if (!iterator1.next().equals(iterator2.next())) {
    532         return false;
    533       }
    534     }
    535     return !iterator2.hasNext();
    536   }
    537 
    538   @SuppressWarnings("unchecked")
    539   private static <T> List<Predicate<? super T>> asList(
    540       Predicate<? super T> first, Predicate<? super T> second) {
    541     return Arrays.<Predicate<? super T>>asList(first, second);
    542   }
    543 
    544   private static <T> List<T> defensiveCopy(T... array) {
    545     return defensiveCopy(Arrays.asList(array));
    546   }
    547 
    548   static <T> List<T> defensiveCopy(Iterable<T> iterable) {
    549     ArrayList<T> list = new ArrayList<T>();
    550     for (T element : iterable) {
    551       list.add(checkNotNull(element));
    552     }
    553     return list;
    554   }
    555 }
    556