001 /*
002 * Copyright (C) 2007 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017 package com.google.common.base;
018
019 import static com.google.common.base.Preconditions.checkNotNull;
020
021 import com.google.common.annotations.Beta;
022 import com.google.common.annotations.GwtCompatible;
023 import com.google.common.annotations.GwtIncompatible;
024
025 import java.io.Serializable;
026 import java.util.ArrayList;
027 import java.util.Arrays;
028 import java.util.Collection;
029 import java.util.List;
030 import java.util.regex.Pattern;
031
032 import javax.annotation.Nullable;
033
034 /**
035 * Static utility methods pertaining to {@code Predicate} instances.
036 *
037 * <p>All methods returns serializable predicates as long as they're given
038 * serializable parameters.
039 *
040 * <p>See the Guava User Guide article on <a href=
041 * "http://code.google.com/p/guava-libraries/wiki/FunctionalExplained">the use of {@code
042 * Predicate}</a>.
043 *
044 * @author Kevin Bourrillion
045 * @since 2.0 (imported from Google Collections Library)
046 */
047 @GwtCompatible(emulated = true)
048 public final class Predicates {
049 private Predicates() {}
050
051 // TODO(kevinb): considering having these implement a VisitablePredicate
052 // interface which specifies an accept(PredicateVisitor) method.
053
054 /**
055 * Returns a predicate that always evaluates to {@code true}.
056 */
057 @GwtCompatible(serializable = true)
058 public static <T> Predicate<T> alwaysTrue() {
059 return ObjectPredicate.ALWAYS_TRUE.withNarrowedType();
060 }
061
062 /**
063 * Returns a predicate that always evaluates to {@code false}.
064 */
065 @GwtCompatible(serializable = true)
066 public static <T> Predicate<T> alwaysFalse() {
067 return ObjectPredicate.ALWAYS_FALSE.withNarrowedType();
068 }
069
070 /**
071 * Returns a predicate that evaluates to {@code true} if the object reference
072 * being tested is null.
073 */
074 @GwtCompatible(serializable = true)
075 public static <T> Predicate<T> isNull() {
076 return ObjectPredicate.IS_NULL.withNarrowedType();
077 }
078
079 /**
080 * Returns a predicate that evaluates to {@code true} if the object reference
081 * being tested is not null.
082 */
083 @GwtCompatible(serializable = true)
084 public static <T> Predicate<T> notNull() {
085 return ObjectPredicate.NOT_NULL.withNarrowedType();
086 }
087
088 /**
089 * Returns a predicate that evaluates to {@code true} if the given predicate
090 * evaluates to {@code false}.
091 */
092 public static <T> Predicate<T> not(Predicate<T> predicate) {
093 return new NotPredicate<T>(predicate);
094 }
095
096 /**
097 * Returns a predicate that evaluates to {@code true} if each of its
098 * components evaluates to {@code true}. The components are evaluated in
099 * 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 */
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 */
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 */
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 */
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 */
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 */
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 */
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")
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
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 */
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 */
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")
255 public static Predicate<CharSequence> containsPattern(String pattern) {
256 return new ContainsPatternPredicate(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")
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 ALWAYS_TRUE {
277 @Override public boolean apply(@Nullable Object o) {
278 return true;
279 }
280 },
281 ALWAYS_FALSE {
282 @Override public boolean apply(@Nullable Object o) {
283 return false;
284 }
285 },
286 IS_NULL {
287 @Override public boolean apply(@Nullable Object o) {
288 return o == null;
289 }
290 },
291 NOT_NULL {
292 @Override public boolean apply(@Nullable Object o) {
293 return o != null;
294 }
295 };
296
297 @SuppressWarnings("unchecked") // these Object predicates work for any T
298 <T> Predicate<T> withNarrowedType() {
299 return (Predicate<T>) this;
300 }
301 }
302
303 /** @see Predicates#not(Predicate) */
304 private static class NotPredicate<T> implements Predicate<T>, Serializable {
305 final Predicate<T> predicate;
306
307 NotPredicate(Predicate<T> predicate) {
308 this.predicate = checkNotNull(predicate);
309 }
310 @Override
311 public boolean apply(T t) {
312 return !predicate.apply(t);
313 }
314 @Override public int hashCode() {
315 return ~predicate.hashCode();
316 }
317 @Override public boolean equals(@Nullable Object obj) {
318 if (obj instanceof NotPredicate) {
319 NotPredicate<?> that = (NotPredicate<?>) obj;
320 return predicate.equals(that.predicate);
321 }
322 return false;
323 }
324 @Override public String toString() {
325 return "Not(" + predicate.toString() + ")";
326 }
327 private static final long serialVersionUID = 0;
328 }
329
330 private static final Joiner COMMA_JOINER = Joiner.on(",");
331
332 /** @see Predicates#and(Iterable) */
333 private static class AndPredicate<T> implements Predicate<T>, Serializable {
334 private final List<? extends Predicate<? super T>> components;
335
336 private AndPredicate(List<? extends Predicate<? super T>> components) {
337 this.components = components;
338 }
339 @Override
340 public boolean apply(T t) {
341 for (int i = 0; i < components.size(); i++) {
342 if (!components.get(i).apply(t)) {
343 return false;
344 }
345 }
346 return true;
347 }
348 @Override public int hashCode() {
349 // 0x12472c2c is a random number to help avoid collisions with OrPredicate
350 return components.hashCode() + 0x12472c2c;
351 }
352 @Override public boolean equals(@Nullable Object obj) {
353 if (obj instanceof AndPredicate) {
354 AndPredicate<?> that = (AndPredicate<?>) obj;
355 return components.equals(that.components);
356 }
357 return false;
358 }
359 @Override public String toString() {
360 return "And(" + COMMA_JOINER.join(components) + ")";
361 }
362 private static final long serialVersionUID = 0;
363 }
364
365 /** @see Predicates#or(Iterable) */
366 private static class OrPredicate<T> implements Predicate<T>, Serializable {
367 private final List<? extends Predicate<? super T>> components;
368
369 private OrPredicate(List<? extends Predicate<? super T>> components) {
370 this.components = components;
371 }
372 @Override
373 public boolean apply(T t) {
374 for (int i = 0; i < components.size(); i++) {
375 if (components.get(i).apply(t)) {
376 return true;
377 }
378 }
379 return false;
380 }
381 @Override public int hashCode() {
382 // 0x053c91cf is a random number to help avoid collisions with AndPredicate
383 return components.hashCode() + 0x053c91cf;
384 }
385 @Override public boolean equals(@Nullable Object obj) {
386 if (obj instanceof OrPredicate) {
387 OrPredicate<?> that = (OrPredicate<?>) obj;
388 return components.equals(that.components);
389 }
390 return false;
391 }
392 @Override public String toString() {
393 return "Or(" + COMMA_JOINER.join(components) + ")";
394 }
395 private static final long serialVersionUID = 0;
396 }
397
398 /** @see Predicates#equalTo(Object) */
399 private static class IsEqualToPredicate<T>
400 implements Predicate<T>, Serializable {
401 private final T target;
402
403 private IsEqualToPredicate(T target) {
404 this.target = target;
405 }
406 @Override
407 public boolean apply(T t) {
408 return target.equals(t);
409 }
410 @Override public int hashCode() {
411 return target.hashCode();
412 }
413 @Override public boolean equals(@Nullable Object obj) {
414 if (obj instanceof IsEqualToPredicate) {
415 IsEqualToPredicate<?> that = (IsEqualToPredicate<?>) obj;
416 return target.equals(that.target);
417 }
418 return false;
419 }
420 @Override public String toString() {
421 return "IsEqualTo(" + target + ")";
422 }
423 private static final long serialVersionUID = 0;
424 }
425
426 /** @see Predicates#instanceOf(Class) */
427 @GwtIncompatible("Class.isInstance")
428 private static class InstanceOfPredicate
429 implements Predicate<Object>, Serializable {
430 private final Class<?> clazz;
431
432 private InstanceOfPredicate(Class<?> clazz) {
433 this.clazz = checkNotNull(clazz);
434 }
435 @Override
436 public boolean apply(@Nullable Object o) {
437 return clazz.isInstance(o);
438 }
439 @Override public int hashCode() {
440 return clazz.hashCode();
441 }
442 @Override public boolean equals(@Nullable Object obj) {
443 if (obj instanceof InstanceOfPredicate) {
444 InstanceOfPredicate that = (InstanceOfPredicate) obj;
445 return clazz == that.clazz;
446 }
447 return false;
448 }
449 @Override public String toString() {
450 return "IsInstanceOf(" + clazz.getName() + ")";
451 }
452 private static final long serialVersionUID = 0;
453 }
454
455 /** @see Predicates#assignableFrom(Class) */
456 @GwtIncompatible("Class.isAssignableFrom")
457 private static class AssignableFromPredicate
458 implements Predicate<Class<?>>, Serializable {
459 private final Class<?> clazz;
460
461 private AssignableFromPredicate(Class<?> clazz) {
462 this.clazz = checkNotNull(clazz);
463 }
464 @Override
465 public boolean apply(Class<?> input) {
466 return clazz.isAssignableFrom(input);
467 }
468 @Override public int hashCode() {
469 return clazz.hashCode();
470 }
471 @Override public boolean equals(@Nullable Object obj) {
472 if (obj instanceof AssignableFromPredicate) {
473 AssignableFromPredicate that = (AssignableFromPredicate) obj;
474 return clazz == that.clazz;
475 }
476 return false;
477 }
478 @Override public String toString() {
479 return "IsAssignableFrom(" + clazz.getName() + ")";
480 }
481 private static final long serialVersionUID = 0;
482 }
483
484 /** @see Predicates#in(Collection) */
485 private static class InPredicate<T> implements Predicate<T>, Serializable {
486 private final Collection<?> target;
487
488 private InPredicate(Collection<?> target) {
489 this.target = checkNotNull(target);
490 }
491
492 @Override
493 public boolean apply(T t) {
494 try {
495 return target.contains(t);
496 } catch (NullPointerException e) {
497 return false;
498 } catch (ClassCastException e) {
499 return false;
500 }
501 }
502
503 @Override public boolean equals(@Nullable Object obj) {
504 if (obj instanceof InPredicate) {
505 InPredicate<?> that = (InPredicate<?>) obj;
506 return target.equals(that.target);
507 }
508 return false;
509 }
510
511 @Override public int hashCode() {
512 return target.hashCode();
513 }
514
515 @Override public String toString() {
516 return "In(" + target + ")";
517 }
518 private static final long serialVersionUID = 0;
519 }
520
521 /** @see Predicates#compose(Predicate, Function) */
522 private static class CompositionPredicate<A, B>
523 implements Predicate<A>, Serializable {
524 final Predicate<B> p;
525 final Function<A, ? extends B> f;
526
527 private CompositionPredicate(Predicate<B> p, Function<A, ? extends B> f) {
528 this.p = checkNotNull(p);
529 this.f = checkNotNull(f);
530 }
531
532 @Override
533 public boolean apply(A a) {
534 return p.apply(f.apply(a));
535 }
536
537 @Override public boolean equals(@Nullable Object obj) {
538 if (obj instanceof CompositionPredicate) {
539 CompositionPredicate<?, ?> that = (CompositionPredicate<?, ?>) obj;
540 return f.equals(that.f) && p.equals(that.p);
541 }
542 return false;
543 }
544
545 @Override public int hashCode() {
546 return f.hashCode() ^ p.hashCode();
547 }
548
549 @Override public String toString() {
550 return p.toString() + "(" + f.toString() + ")";
551 }
552
553 private static final long serialVersionUID = 0;
554 }
555
556 /**
557 * @see Predicates#contains(Pattern)
558 * @see Predicates#containsPattern(String)
559 */
560 @GwtIncompatible("Only used by other GWT-incompatible code.")
561 private static class ContainsPatternPredicate
562 implements Predicate<CharSequence>, Serializable {
563 final Pattern pattern;
564
565 ContainsPatternPredicate(Pattern pattern) {
566 this.pattern = checkNotNull(pattern);
567 }
568
569 ContainsPatternPredicate(String patternStr) {
570 this(Pattern.compile(patternStr));
571 }
572
573 @Override
574 public boolean apply(CharSequence t) {
575 return pattern.matcher(t).find();
576 }
577
578 @Override public int hashCode() {
579 // Pattern uses Object.hashCode, so we have to reach
580 // inside to build a hashCode consistent with equals.
581
582 return Objects.hashCode(pattern.pattern(), pattern.flags());
583 }
584
585 @Override public boolean equals(@Nullable Object obj) {
586 if (obj instanceof ContainsPatternPredicate) {
587 ContainsPatternPredicate that = (ContainsPatternPredicate) obj;
588
589 // Pattern uses Object (identity) equality, so we have to reach
590 // inside to compare individual fields.
591 return Objects.equal(pattern.pattern(), that.pattern.pattern())
592 && Objects.equal(pattern.flags(), that.pattern.flags());
593 }
594 return false;
595 }
596
597 @Override public String toString() {
598 return Objects.toStringHelper(this)
599 .add("pattern", pattern)
600 .add("pattern.flags", Integer.toHexString(pattern.flags()))
601 .toString();
602 }
603
604 private static final long serialVersionUID = 0;
605 }
606
607 @SuppressWarnings("unchecked")
608 private static <T> List<Predicate<? super T>> asList(
609 Predicate<? super T> first, Predicate<? super T> second) {
610 return Arrays.<Predicate<? super T>>asList(first, second);
611 }
612
613 private static <T> List<T> defensiveCopy(T... array) {
614 return defensiveCopy(Arrays.asList(array));
615 }
616
617 static <T> List<T> defensiveCopy(Iterable<T> iterable) {
618 ArrayList<T> list = new ArrayList<T>();
619 for (T element : iterable) {
620 list.add(checkNotNull(element));
621 }
622 return list;
623 }
624 }