• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2007 The Guava Authors
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of 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,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.google.common.base;
18 
19 import static com.google.common.base.Preconditions.checkNotNull;
20 
21 import com.google.common.annotations.Beta;
22 import com.google.common.annotations.GwtCompatible;
23 import com.google.common.annotations.GwtIncompatible;
24 
25 import java.io.Serializable;
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.Collection;
29 import java.util.List;
30 import java.util.regex.Pattern;
31 
32 import javax.annotation.Nullable;
33 
34 /**
35  * Static utility methods pertaining to {@code Predicate} instances.
36  *
37  * <p>All methods returns serializable predicates as long as they're given
38  * serializable parameters.
39  *
40  * <p>See the Guava User Guide article on <a href=
41  * "http://code.google.com/p/guava-libraries/wiki/FunctionalExplained">the
42  * use of {@code Predicate}</a>.
43  *
44  * @author Kevin Bourrillion
45  * @since 2.0 (imported from Google Collections Library)
46  */
47 @GwtCompatible(emulated = true)
48 public final class Predicates {
Predicates()49   private Predicates() {}
50 
51   // TODO(kevinb): considering having these implement a VisitablePredicate
52   // interface which specifies an accept(PredicateVisitor) method.
53 
54   /**
55    * Returns a predicate that always evaluates to {@code true}.
56    */
57   @GwtCompatible(serializable = true)
alwaysTrue()58   public static <T> Predicate<T> alwaysTrue() {
59     return ObjectPredicate.ALWAYS_TRUE.withNarrowedType();
60   }
61 
62   /**
63    * Returns a predicate that always evaluates to {@code false}.
64    */
65   @GwtCompatible(serializable = true)
alwaysFalse()66   public static <T> Predicate<T> alwaysFalse() {
67     return ObjectPredicate.ALWAYS_FALSE.withNarrowedType();
68   }
69 
70   /**
71    * Returns a predicate that evaluates to {@code true} if the object reference
72    * being tested is null.
73    */
74   @GwtCompatible(serializable = true)
isNull()75   public static <T> Predicate<T> isNull() {
76     return ObjectPredicate.IS_NULL.withNarrowedType();
77   }
78 
79   /**
80    * Returns a predicate that evaluates to {@code true} if the object reference
81    * being tested is not null.
82    */
83   @GwtCompatible(serializable = true)
notNull()84   public static <T> Predicate<T> notNull() {
85     return ObjectPredicate.NOT_NULL.withNarrowedType();
86   }
87 
88   /**
89    * Returns a predicate that evaluates to {@code true} if the given predicate
90    * evaluates to {@code false}.
91    */
not(Predicate<T> predicate)92   public static <T> Predicate<T> not(Predicate<T> predicate) {
93     return new NotPredicate<T>(predicate);
94   }
95 
96   /**
97    * Returns a predicate that evaluates to {@code true} if each of its
98    * components evaluates to {@code true}. The components are evaluated in
99    * order, and evaluation will be "short-circuited" as soon as a false
100    * predicate is found. It defensively copies the iterable passed in, so future
101    * changes to it won't alter the behavior of this predicate. If {@code
102    * components} is empty, the returned predicate will always evaluate to {@code
103    * true}.
104    */
and( Iterable<? extends Predicate<? super T>> components)105   public static <T> Predicate<T> and(
106       Iterable<? extends Predicate<? super T>> components) {
107     return new AndPredicate<T>(defensiveCopy(components));
108   }
109 
110   /**
111    * Returns a predicate that evaluates to {@code true} if each of its
112    * components evaluates to {@code true}. The components are evaluated in
113    * order, and evaluation will be "short-circuited" as soon as a false
114    * predicate is found. It defensively copies the array passed in, so future
115    * changes to it won't alter the behavior of this predicate. If {@code
116    * components} is empty, the returned predicate will always evaluate to {@code
117    * true}.
118    */
and(Predicate<? super T>.... components)119   public static <T> Predicate<T> and(Predicate<? super T>... components) {
120     return new AndPredicate<T>(defensiveCopy(components));
121   }
122 
123   /**
124    * Returns a predicate that evaluates to {@code true} if both of its
125    * components evaluate to {@code true}. The components are evaluated in
126    * order, and evaluation will be "short-circuited" as soon as a false
127    * predicate is found.
128    */
and(Predicate<? super T> first, Predicate<? super T> second)129   public static <T> Predicate<T> and(Predicate<? super T> first,
130       Predicate<? super T> second) {
131     return new AndPredicate<T>(Predicates.<T>asList(
132         checkNotNull(first), checkNotNull(second)));
133   }
134 
135   /**
136    * Returns a predicate that evaluates to {@code true} if any one of its
137    * components evaluates to {@code true}. The components are evaluated in
138    * order, and evaluation will be "short-circuited" as soon as a
139    * true predicate is found. It defensively copies the iterable passed in, so
140    * future changes to it won't alter the behavior of this predicate. If {@code
141    * components} is empty, the returned predicate will always evaluate to {@code
142    * false}.
143    */
or( Iterable<? extends Predicate<? super T>> components)144   public static <T> Predicate<T> or(
145       Iterable<? extends Predicate<? super T>> components) {
146     return new OrPredicate<T>(defensiveCopy(components));
147   }
148 
149   /**
150    * Returns a predicate that evaluates to {@code true} if any one of its
151    * components evaluates to {@code true}. The components are evaluated in
152    * order, and evaluation will be "short-circuited" as soon as a
153    * true predicate is found. It defensively copies the array passed in, so
154    * future changes to it won't alter the behavior of this predicate. If {@code
155    * components} is empty, the returned predicate will always evaluate to {@code
156    * false}.
157    */
or(Predicate<? super T>.... components)158   public static <T> Predicate<T> or(Predicate<? super T>... components) {
159     return new OrPredicate<T>(defensiveCopy(components));
160   }
161 
162   /**
163    * Returns a predicate that evaluates to {@code true} if either of its
164    * components evaluates to {@code true}. The components are evaluated in
165    * order, and evaluation will be "short-circuited" as soon as a
166    * true predicate is found.
167    */
or( Predicate<? super T> first, Predicate<? super T> second)168   public static <T> Predicate<T> or(
169       Predicate<? super T> first, Predicate<? super T> second) {
170     return new OrPredicate<T>(Predicates.<T>asList(
171         checkNotNull(first), checkNotNull(second)));
172   }
173 
174   /**
175    * Returns a predicate that evaluates to {@code true} if the object being
176    * tested {@code equals()} the given target or both are null.
177    */
equalTo(@ullable T target)178   public static <T> Predicate<T> equalTo(@Nullable T target) {
179     return (target == null)
180         ? Predicates.<T>isNull()
181         : new IsEqualToPredicate<T>(target);
182   }
183 
184   /**
185    * Returns a predicate that evaluates to {@code true} if the object being
186    * tested is an instance of the given class. If the object being tested
187    * is {@code null} this predicate evaluates to {@code false}.
188    *
189    * <p>If you want to filter an {@code Iterable} to narrow its type, consider
190    * using {@link com.google.common.collect.Iterables#filter(Iterable, Class)}
191    * in preference.
192    *
193    * <p><b>Warning:</b> contrary to the typical assumptions about predicates (as
194    * documented at {@link Predicate#apply}), the returned predicate may not be
195    * <i>consistent with equals</i>. For example, {@code
196    * instanceOf(ArrayList.class)} will yield different results for the two equal
197    * instances {@code Lists.newArrayList(1)} and {@code Arrays.asList(1)}.
198    */
199   @GwtIncompatible("Class.isInstance")
instanceOf(Class<?> clazz)200   public static Predicate<Object> instanceOf(Class<?> clazz) {
201     return new InstanceOfPredicate(clazz);
202   }
203 
204   /**
205    * Returns a predicate that evaluates to {@code true} if the class being
206    * tested is assignable from the given class.  The returned predicate
207    * does not allow null inputs.
208    *
209    * @since 10.0
210    */
211   @GwtIncompatible("Class.isAssignableFrom")
212   @Beta
assignableFrom(Class<?> clazz)213   public static Predicate<Class<?>> assignableFrom(Class<?> clazz) {
214     return new AssignableFromPredicate(clazz);
215   }
216 
217   /**
218    * Returns a predicate that evaluates to {@code true} if the object reference
219    * being tested is a member of the given collection. It does not defensively
220    * copy the collection passed in, so future changes to it will alter the
221    * behavior of the predicate.
222    *
223    * <p>This method can technically accept any {@code Collection<?>}, but using
224    * a typed collection helps prevent bugs. This approach doesn't block any
225    * potential users since it is always possible to use {@code
226    * Predicates.<Object>in()}.
227    *
228    * @param target the collection that may contain the function input
229    */
in(Collection<? extends T> target)230   public static <T> Predicate<T> in(Collection<? extends T> target) {
231     return new InPredicate<T>(target);
232   }
233 
234   /**
235    * Returns the composition of a function and a predicate. For every {@code x},
236    * the generated predicate returns {@code predicate(function(x))}.
237    *
238    * @return the composition of the provided function and predicate
239    */
compose( Predicate<B> predicate, Function<A, ? extends B> function)240   public static <A, B> Predicate<A> compose(
241       Predicate<B> predicate, Function<A, ? extends B> function) {
242     return new CompositionPredicate<A, B>(predicate, function);
243   }
244 
245   /**
246    * Returns a predicate that evaluates to {@code true} if the
247    * {@code CharSequence} being tested contains any match for the given
248    * regular expression pattern. The test used is equivalent to
249    * {@code Pattern.compile(pattern).matcher(arg).find()}
250    *
251    * @throws java.util.regex.PatternSyntaxException if the pattern is invalid
252    * @since 3.0
253    */
254   @GwtIncompatible(value = "java.util.regex.Pattern")
containsPattern(String pattern)255   public static Predicate<CharSequence> containsPattern(String pattern) {
256     return new ContainsPatternFromStringPredicate(pattern);
257   }
258 
259   /**
260    * Returns a predicate that evaluates to {@code true} if the
261    * {@code CharSequence} being tested contains any match for the given
262    * regular expression pattern. The test used is equivalent to
263    * {@code pattern.matcher(arg).find()}
264    *
265    * @since 3.0
266    */
267   @GwtIncompatible(value = "java.util.regex.Pattern")
contains(Pattern pattern)268   public static Predicate<CharSequence> contains(Pattern pattern) {
269     return new ContainsPatternPredicate(pattern);
270   }
271 
272   // End public API, begin private implementation classes.
273 
274   // Package private for GWT serialization.
275   enum ObjectPredicate implements Predicate<Object> {
276     /** @see Predicates#alwaysTrue() */
277     ALWAYS_TRUE {
apply(@ullable Object o)278       @Override public boolean apply(@Nullable Object o) {
279         return true;
280       }
toString()281       @Override public String toString() {
282         return "Predicates.alwaysTrue()";
283       }
284     },
285     /** @see Predicates#alwaysFalse() */
286     ALWAYS_FALSE {
apply(@ullable Object o)287       @Override public boolean apply(@Nullable Object o) {
288         return false;
289       }
toString()290       @Override public String toString() {
291         return "Predicates.alwaysFalse()";
292       }
293     },
294     /** @see Predicates#isNull() */
295     IS_NULL {
apply(@ullable Object o)296       @Override public boolean apply(@Nullable Object o) {
297         return o == null;
298       }
toString()299       @Override public String toString() {
300         return "Predicates.isNull()";
301       }
302     },
303     /** @see Predicates#notNull() */
304     NOT_NULL {
apply(@ullable Object o)305       @Override public boolean apply(@Nullable Object o) {
306         return o != null;
307       }
toString()308       @Override public String toString() {
309         return "Predicates.notNull()";
310       }
311     };
312 
313     @SuppressWarnings("unchecked") // safe contravariant cast
withNarrowedType()314     <T> Predicate<T> withNarrowedType() {
315       return (Predicate<T>) this;
316     }
317   }
318 
319   /** @see Predicates#not(Predicate) */
320   private static class NotPredicate<T> implements Predicate<T>, Serializable {
321     final Predicate<T> predicate;
322 
NotPredicate(Predicate<T> predicate)323     NotPredicate(Predicate<T> predicate) {
324       this.predicate = checkNotNull(predicate);
325     }
326     @Override
apply(@ullable T t)327     public boolean apply(@Nullable T t) {
328       return !predicate.apply(t);
329     }
hashCode()330     @Override public int hashCode() {
331       return ~predicate.hashCode();
332     }
equals(@ullable Object obj)333     @Override public boolean equals(@Nullable Object obj) {
334       if (obj instanceof NotPredicate) {
335         NotPredicate<?> that = (NotPredicate<?>) obj;
336         return predicate.equals(that.predicate);
337       }
338       return false;
339     }
toString()340     @Override public String toString() {
341       return "Predicates.not(" + predicate.toString() + ")";
342     }
343     private static final long serialVersionUID = 0;
344   }
345 
346   private static final Joiner COMMA_JOINER = Joiner.on(',');
347 
348   /** @see Predicates#and(Iterable) */
349   private static class AndPredicate<T> implements Predicate<T>, Serializable {
350     private final List<? extends Predicate<? super T>> components;
351 
AndPredicate(List<? extends Predicate<? super T>> components)352     private AndPredicate(List<? extends Predicate<? super T>> components) {
353       this.components = components;
354     }
355     @Override
apply(@ullable T t)356     public boolean apply(@Nullable T t) {
357       // Avoid using the Iterator to avoid generating garbage (issue 820).
358       for (int i = 0; i < components.size(); i++) {
359         if (!components.get(i).apply(t)) {
360           return false;
361         }
362       }
363       return true;
364     }
hashCode()365     @Override public int hashCode() {
366       // add a random number to avoid collisions with OrPredicate
367       return components.hashCode() + 0x12472c2c;
368     }
equals(@ullable Object obj)369     @Override public boolean equals(@Nullable Object obj) {
370       if (obj instanceof AndPredicate) {
371         AndPredicate<?> that = (AndPredicate<?>) obj;
372         return components.equals(that.components);
373       }
374       return false;
375     }
toString()376     @Override public String toString() {
377       return "Predicates.and(" + COMMA_JOINER.join(components) + ")";
378     }
379     private static final long serialVersionUID = 0;
380   }
381 
382   /** @see Predicates#or(Iterable) */
383   private static class OrPredicate<T> implements Predicate<T>, Serializable {
384     private final List<? extends Predicate<? super T>> components;
385 
OrPredicate(List<? extends Predicate<? super T>> components)386     private OrPredicate(List<? extends Predicate<? super T>> components) {
387       this.components = components;
388     }
389     @Override
apply(@ullable T t)390     public boolean apply(@Nullable T t) {
391       // Avoid using the Iterator to avoid generating garbage (issue 820).
392       for (int i = 0; i < components.size(); i++) {
393         if (components.get(i).apply(t)) {
394           return true;
395         }
396       }
397       return false;
398     }
hashCode()399     @Override public int hashCode() {
400       // add a random number to avoid collisions with AndPredicate
401       return components.hashCode() + 0x053c91cf;
402     }
equals(@ullable Object obj)403     @Override public boolean equals(@Nullable Object obj) {
404       if (obj instanceof OrPredicate) {
405         OrPredicate<?> that = (OrPredicate<?>) obj;
406         return components.equals(that.components);
407       }
408       return false;
409     }
toString()410     @Override public String toString() {
411       return "Predicates.or(" + COMMA_JOINER.join(components) + ")";
412     }
413     private static final long serialVersionUID = 0;
414   }
415 
416   /** @see Predicates#equalTo(Object) */
417   private static class IsEqualToPredicate<T>
418       implements Predicate<T>, Serializable {
419     private final T target;
420 
IsEqualToPredicate(T target)421     private IsEqualToPredicate(T target) {
422       this.target = target;
423     }
424     @Override
apply(T t)425     public boolean apply(T t) {
426       return target.equals(t);
427     }
hashCode()428     @Override public int hashCode() {
429       return target.hashCode();
430     }
equals(@ullable Object obj)431     @Override public boolean equals(@Nullable Object obj) {
432       if (obj instanceof IsEqualToPredicate) {
433         IsEqualToPredicate<?> that = (IsEqualToPredicate<?>) obj;
434         return target.equals(that.target);
435       }
436       return false;
437     }
toString()438     @Override public String toString() {
439       return "Predicates.equalTo(" + target + ")";
440     }
441     private static final long serialVersionUID = 0;
442   }
443 
444   /** @see Predicates#instanceOf(Class) */
445   @GwtIncompatible("Class.isInstance")
446   private static class InstanceOfPredicate
447       implements Predicate<Object>, Serializable {
448     private final Class<?> clazz;
449 
InstanceOfPredicate(Class<?> clazz)450     private InstanceOfPredicate(Class<?> clazz) {
451       this.clazz = checkNotNull(clazz);
452     }
453     @Override
apply(@ullable Object o)454     public boolean apply(@Nullable Object o) {
455       return clazz.isInstance(o);
456     }
hashCode()457     @Override public int hashCode() {
458       return clazz.hashCode();
459     }
equals(@ullable Object obj)460     @Override public boolean equals(@Nullable Object obj) {
461       if (obj instanceof InstanceOfPredicate) {
462         InstanceOfPredicate that = (InstanceOfPredicate) obj;
463         return clazz == that.clazz;
464       }
465       return false;
466     }
toString()467     @Override public String toString() {
468       return "Predicates.instanceOf(" + clazz.getName() + ")";
469     }
470     private static final long serialVersionUID = 0;
471   }
472 
473   /** @see Predicates#assignableFrom(Class) */
474   @GwtIncompatible("Class.isAssignableFrom")
475   private static class AssignableFromPredicate
476       implements Predicate<Class<?>>, Serializable {
477     private final Class<?> clazz;
478 
AssignableFromPredicate(Class<?> clazz)479     private AssignableFromPredicate(Class<?> clazz) {
480       this.clazz = checkNotNull(clazz);
481     }
482     @Override
apply(Class<?> input)483     public boolean apply(Class<?> input) {
484       return clazz.isAssignableFrom(input);
485     }
hashCode()486     @Override public int hashCode() {
487       return clazz.hashCode();
488     }
equals(@ullable Object obj)489     @Override public boolean equals(@Nullable Object obj) {
490       if (obj instanceof AssignableFromPredicate) {
491         AssignableFromPredicate that = (AssignableFromPredicate) obj;
492         return clazz == that.clazz;
493       }
494       return false;
495     }
toString()496     @Override public String toString() {
497       return "Predicates.assignableFrom(" + clazz.getName() + ")";
498     }
499     private static final long serialVersionUID = 0;
500   }
501 
502   /** @see Predicates#in(Collection) */
503   private static class InPredicate<T> implements Predicate<T>, Serializable {
504     private final Collection<?> target;
505 
InPredicate(Collection<?> target)506     private InPredicate(Collection<?> target) {
507       this.target = checkNotNull(target);
508     }
509 
510     @Override
apply(@ullable T t)511     public boolean apply(@Nullable T t) {
512       try {
513         return target.contains(t);
514       } catch (NullPointerException e) {
515         return false;
516       } catch (ClassCastException e) {
517         return false;
518       }
519     }
520 
equals(@ullable Object obj)521     @Override public boolean equals(@Nullable Object obj) {
522       if (obj instanceof InPredicate) {
523         InPredicate<?> that = (InPredicate<?>) obj;
524         return target.equals(that.target);
525       }
526       return false;
527     }
528 
hashCode()529     @Override public int hashCode() {
530       return target.hashCode();
531     }
532 
toString()533     @Override public String toString() {
534       return "Predicates.in(" + target + ")";
535     }
536     private static final long serialVersionUID = 0;
537   }
538 
539   /** @see Predicates#compose(Predicate, Function) */
540   private static class CompositionPredicate<A, B>
541       implements Predicate<A>, Serializable {
542     final Predicate<B> p;
543     final Function<A, ? extends B> f;
544 
CompositionPredicate(Predicate<B> p, Function<A, ? extends B> f)545     private CompositionPredicate(Predicate<B> p, Function<A, ? extends B> f) {
546       this.p = checkNotNull(p);
547       this.f = checkNotNull(f);
548     }
549 
550     @Override
apply(@ullable A a)551     public boolean apply(@Nullable A a) {
552       return p.apply(f.apply(a));
553     }
554 
equals(@ullable Object obj)555     @Override public boolean equals(@Nullable Object obj) {
556       if (obj instanceof CompositionPredicate) {
557         CompositionPredicate<?, ?> that = (CompositionPredicate<?, ?>) obj;
558         return f.equals(that.f) && p.equals(that.p);
559       }
560       return false;
561     }
562 
hashCode()563     @Override public int hashCode() {
564       return f.hashCode() ^ p.hashCode();
565     }
566 
toString()567     @Override public String toString() {
568       return p.toString() + "(" + f.toString() + ")";
569     }
570 
571     private static final long serialVersionUID = 0;
572   }
573 
574   /** @see Predicates#contains(Pattern) */
575   @GwtIncompatible("Only used by other GWT-incompatible code.")
576   private static class ContainsPatternPredicate
577       implements Predicate<CharSequence>, Serializable {
578     final Pattern pattern;
579 
ContainsPatternPredicate(Pattern pattern)580     ContainsPatternPredicate(Pattern pattern) {
581       this.pattern = checkNotNull(pattern);
582     }
583 
584     @Override
apply(CharSequence t)585     public boolean apply(CharSequence t) {
586       return pattern.matcher(t).find();
587     }
588 
hashCode()589     @Override public int hashCode() {
590       // Pattern uses Object.hashCode, so we have to reach
591       // inside to build a hashCode consistent with equals.
592 
593       return Objects.hashCode(pattern.pattern(), pattern.flags());
594     }
595 
equals(@ullable Object obj)596     @Override public boolean equals(@Nullable Object obj) {
597       if (obj instanceof ContainsPatternPredicate) {
598         ContainsPatternPredicate that = (ContainsPatternPredicate) obj;
599 
600         // Pattern uses Object (identity) equality, so we have to reach
601         // inside to compare individual fields.
602         return Objects.equal(pattern.pattern(), that.pattern.pattern())
603             && Objects.equal(pattern.flags(), that.pattern.flags());
604       }
605       return false;
606     }
607 
toString()608     @Override public String toString() {
609       String patternString = Objects.toStringHelper(pattern)
610           .add("pattern", pattern.pattern())
611           .add("pattern.flags", pattern.flags())
612           .toString();
613       return "Predicates.contains(" + patternString + ")";
614     }
615 
616     private static final long serialVersionUID = 0;
617   }
618 
619   /** @see Predicates#containsPattern(String) */
620   @GwtIncompatible("Only used by other GWT-incompatible code.")
621   private static class ContainsPatternFromStringPredicate
622       extends ContainsPatternPredicate {
623 
ContainsPatternFromStringPredicate(String string)624     ContainsPatternFromStringPredicate(String string) {
625       super(Pattern.compile(string));
626     }
627 
toString()628     @Override public String toString() {
629       return "Predicates.containsPattern(" + pattern.pattern() + ")";
630     }
631 
632     private static final long serialVersionUID = 0;
633   }
634 
asList( Predicate<? super T> first, Predicate<? super T> second)635   private static <T> List<Predicate<? super T>> asList(
636       Predicate<? super T> first, Predicate<? super T> second) {
637     // TODO(kevinb): understand why we still get a warning despite @SafeVarargs!
638     return Arrays.<Predicate<? super T>>asList(first, second);
639   }
640 
defensiveCopy(T... array)641   private static <T> List<T> defensiveCopy(T... array) {
642     return defensiveCopy(Arrays.asList(array));
643   }
644 
defensiveCopy(Iterable<T> iterable)645   static <T> List<T> defensiveCopy(Iterable<T> iterable) {
646     ArrayList<T> list = new ArrayList<T>();
647     for (T element : iterable) {
648       list.add(checkNotNull(element));
649     }
650     return list;
651   }
652 }
653