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
042 * use of {@code 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 public boolean apply(@Nullable Object o) {
278 return true;
279 }
280 },
281 ALWAYS_FALSE {
282 public boolean apply(@Nullable Object o) {
283 return false;
284 }
285 },
286 IS_NULL {
287 public boolean apply(@Nullable Object o) {
288 return o == null;
289 }
290 },
291 NOT_NULL {
292 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 public boolean apply(T t) {
311 return !predicate.apply(t);
312 }
313
314 @Override
315 public int hashCode() {
316 return ~predicate.hashCode();
317 }
318
319 @Override
320 public boolean equals(@Nullable Object obj) {
321 if (obj instanceof NotPredicate) {
322 NotPredicate<?> that = (NotPredicate<?>) obj;
323 return predicate.equals(that.predicate);
324 }
325 return false;
326 }
327
328 @Override
329 public String toString() {
330 return "Not(" + predicate.toString() + ")";
331 }
332 private static final long serialVersionUID = 0;
333 }
334
335 private static final Joiner COMMA_JOINER = Joiner.on(",");
336
337 /** @see Predicates#and(Iterable) */
338 private static class AndPredicate<T> implements Predicate<T>, Serializable {
339 private final List<? extends Predicate<? super T>> components;
340
341 private AndPredicate(List<? extends Predicate<? super T>> components) {
342 this.components = components;
343 }
344 public boolean apply(T t) {
345 // Avoid using the Iterator to avoid generating garbage (issue 820).
346 for (int i = 0; i < components.size(); i++) {
347 if (!components.get(i).apply(t)) {
348 return false;
349 }
350 }
351 return true;
352 }
353 @Override
354 public int hashCode() {
355 // add a random number to avoid collisions with OrPredicate
356 return components.hashCode() + 0x12472c2c;
357 }
358
359 @Override
360 public boolean equals(@Nullable Object obj) {
361 if (obj instanceof AndPredicate) {
362 AndPredicate<?> that = (AndPredicate<?>) obj;
363 return components.equals(that.components);
364 }
365 return false;
366 }
367
368 @Override
369 public String toString() {
370 return "And(" + COMMA_JOINER.join(components) + ")";
371 }
372 private static final long serialVersionUID = 0;
373 }
374
375 /** @see Predicates#or(Iterable) */
376 private static class OrPredicate<T> implements Predicate<T>, Serializable {
377 private final List<? extends Predicate<? super T>> components;
378
379 private OrPredicate(List<? extends Predicate<? super T>> components) {
380 this.components = components;
381 }
382 public boolean apply(T t) {
383 // Avoid using the Iterator to avoid generating garbage (issue 820).
384 for (int i = 0; i < components.size(); i++) {
385 if (components.get(i).apply(t)) {
386 return true;
387 }
388 }
389 return false;
390 }
391 @Override
392 public int hashCode() {
393 // add a random number to avoid collisions with AndPredicate
394 return components.hashCode() + 0x053c91cf;
395 }
396
397 @Override
398 public boolean equals(@Nullable Object obj) {
399 if (obj instanceof OrPredicate) {
400 OrPredicate<?> that = (OrPredicate<?>) obj;
401 return components.equals(that.components);
402 }
403 return false;
404 }
405
406 @Override
407 public String toString() {
408 return "Or(" + COMMA_JOINER.join(components) + ")";
409 }
410 private static final long serialVersionUID = 0;
411 }
412
413 /** @see Predicates#equalTo(Object) */
414 private static class IsEqualToPredicate<T>
415 implements Predicate<T>, Serializable {
416 private final T target;
417
418 private IsEqualToPredicate(T target) {
419 this.target = target;
420 }
421 public boolean apply(T t) {
422 return target.equals(t);
423 }
424
425 @Override
426 public int hashCode() {
427 return target.hashCode();
428 }
429
430 @Override
431 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 }
438
439 @Override
440 public String toString() {
441 return "IsEqualTo(" + target + ")";
442 }
443 private static final long serialVersionUID = 0;
444 }
445
446 /** @see Predicates#instanceOf(Class) */
447 @GwtIncompatible("Class.isInstance")
448 private static class InstanceOfPredicate
449 implements Predicate<Object>, Serializable {
450 private final Class<?> clazz;
451
452 private InstanceOfPredicate(Class<?> clazz) {
453 this.clazz = checkNotNull(clazz);
454 }
455 public boolean apply(@Nullable Object o) {
456 return clazz.isInstance(o);
457 }
458
459 @Override
460 public int hashCode() {
461 return clazz.hashCode();
462 }
463
464 @Override
465 public boolean equals(@Nullable Object obj) {
466 if (obj instanceof InstanceOfPredicate) {
467 InstanceOfPredicate that = (InstanceOfPredicate) obj;
468 return clazz == that.clazz;
469 }
470 return false;
471 }
472
473 @Override
474 public String toString() {
475 return "IsInstanceOf(" + clazz.getName() + ")";
476 }
477 private static final long serialVersionUID = 0;
478 }
479
480 /** @see Predicates#assignableFrom(Class) */
481 @GwtIncompatible("Class.isAssignableFrom")
482 private static class AssignableFromPredicate
483 implements Predicate<Class<?>>, Serializable {
484 private final Class<?> clazz;
485
486 private AssignableFromPredicate(Class<?> clazz) {
487 this.clazz = checkNotNull(clazz);
488 }
489 public boolean apply(Class<?> input) {
490 return clazz.isAssignableFrom(input);
491 }
492
493 @Override
494 public int hashCode() {
495 return clazz.hashCode();
496 }
497
498 @Override
499 public boolean equals(@Nullable Object obj) {
500 if (obj instanceof AssignableFromPredicate) {
501 AssignableFromPredicate that = (AssignableFromPredicate) obj;
502 return clazz == that.clazz;
503 }
504 return false;
505 }
506
507 @Override
508 public String toString() {
509 return "IsAssignableFrom(" + clazz.getName() + ")";
510 }
511 private static final long serialVersionUID = 0;
512 }
513
514 /** @see Predicates#in(Collection) */
515 private static class InPredicate<T> implements Predicate<T>, Serializable {
516 private final Collection<?> target;
517
518 private InPredicate(Collection<?> target) {
519 this.target = checkNotNull(target);
520 }
521
522 public boolean apply(T t) {
523 try {
524 return target.contains(t);
525 } catch (NullPointerException e) {
526 return false;
527 } catch (ClassCastException e) {
528 return false;
529 }
530 }
531
532
533 @Override
534 public boolean equals(@Nullable Object obj) {
535 if (obj instanceof InPredicate) {
536 InPredicate<?> that = (InPredicate<?>) obj;
537 return target.equals(that.target);
538 }
539 return false;
540 }
541
542
543 @Override
544 public int hashCode() {
545 return target.hashCode();
546 }
547
548
549 @Override
550 public String toString() {
551 return "In(" + target + ")";
552 }
553 private static final long serialVersionUID = 0;
554 }
555
556 /** @see Predicates#compose(Predicate, Function) */
557 private static class CompositionPredicate<A, B>
558 implements Predicate<A>, Serializable {
559 final Predicate<B> p;
560 final Function<A, ? extends B> f;
561
562 private CompositionPredicate(Predicate<B> p, Function<A, ? extends B> f) {
563 this.p = checkNotNull(p);
564 this.f = checkNotNull(f);
565 }
566
567 public boolean apply(A a) {
568 return p.apply(f.apply(a));
569 }
570
571
572 @Override
573 public boolean equals(@Nullable Object obj) {
574 if (obj instanceof CompositionPredicate) {
575 CompositionPredicate<?, ?> that = (CompositionPredicate<?, ?>) obj;
576 return f.equals(that.f) && p.equals(that.p);
577 }
578 return false;
579 }
580
581
582 @Override
583 public int hashCode() {
584 return f.hashCode() ^ p.hashCode();
585 }
586
587
588 @Override
589 public String toString() {
590 return p.toString() + "(" + f.toString() + ")";
591 }
592
593 private static final long serialVersionUID = 0;
594 }
595
596 /**
597 * @see Predicates#contains(Pattern)
598 * @see Predicates#containsPattern(String)
599 */
600 @GwtIncompatible("Only used by other GWT-incompatible code.")
601 private static class ContainsPatternPredicate
602 implements Predicate<CharSequence>, Serializable {
603 final Pattern pattern;
604
605 ContainsPatternPredicate(Pattern pattern) {
606 this.pattern = checkNotNull(pattern);
607 }
608
609 ContainsPatternPredicate(String patternStr) {
610 this(Pattern.compile(patternStr));
611 }
612
613 public boolean apply(CharSequence t) {
614 return pattern.matcher(t).find();
615 }
616
617
618 @Override
619 public int hashCode() {
620 // Pattern uses Object.hashCode, so we have to reach
621 // inside to build a hashCode consistent with equals.
622
623 return Objects.hashCode(pattern.pattern(), pattern.flags());
624 }
625
626
627 @Override
628 public boolean equals(@Nullable Object obj) {
629 if (obj instanceof ContainsPatternPredicate) {
630 ContainsPatternPredicate that = (ContainsPatternPredicate) obj;
631
632 // Pattern uses Object (identity) equality, so we have to reach
633 // inside to compare individual fields.
634 return Objects.equal(pattern.pattern(), that.pattern.pattern())
635 && Objects.equal(pattern.flags(), that.pattern.flags());
636 }
637 return false;
638 }
639
640
641 @Override
642 public String toString() {
643 return Objects.toStringHelper(this)
644 .add("pattern", pattern)
645 .add("pattern.flags", Integer.toHexString(pattern.flags()))
646 .toString();
647 }
648
649 private static final long serialVersionUID = 0;
650 }
651
652 @SuppressWarnings("unchecked")
653 private static <T> List<Predicate<? super T>> asList(
654 Predicate<? super T> first, Predicate<? super T> second) {
655 return Arrays.<Predicate<? super T>>asList(first, second);
656 }
657
658 private static <T> List<T> defensiveCopy(T... array) {
659 return defensiveCopy(Arrays.asList(array));
660 }
661
662 static <T> List<T> defensiveCopy(Iterable<T> iterable) {
663 ArrayList<T> list = new ArrayList<T>();
664 for (T element : iterable) {
665 list.add(checkNotNull(element));
666 }
667 return list;
668 }
669 }