001 /*
002 * Copyright (C) 2007 Google Inc.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
005 * use this file except in compliance with the License. You may obtain a copy of
006 * 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, WITHOUT
012 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
013 * License for the specific language governing permissions and limitations under
014 * 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.Iterator;
030 import java.util.List;
031 import java.util.regex.Pattern;
032
033 import javax.annotation.Nullable;
034
035 /**
036 * Contains static factory methods for creating {@code Predicate} instances.
037 *
038 * <p>All methods returns serializable predicates as long as they're given
039 * serializable parameters.
040 *
041 * @author Kevin Bourrillion
042 * @since 2 (imported from Google Collections Library)
043 */
044 @GwtCompatible
045 public final class Predicates {
046 private Predicates() {}
047
048 // TODO: considering having these implement a VisitablePredicate interface
049 // which specifies an accept(PredicateVisitor) method.
050
051 /**
052 * Returns a predicate that always evaluates to {@code true}.
053 */
054 @GwtCompatible(serializable = true)
055 @SuppressWarnings("unchecked")
056 public static <T> Predicate<T> alwaysTrue() {
057 return (Predicate<T>) AlwaysTruePredicate.INSTANCE;
058 }
059
060 /**
061 * Returns a predicate that always evaluates to {@code false}.
062 */
063 @GwtCompatible(serializable = true)
064 @SuppressWarnings("unchecked")
065 public static <T> Predicate<T> alwaysFalse() {
066 return (Predicate<T>) AlwaysFalsePredicate.INSTANCE;
067 }
068
069 /**
070 * Returns a predicate that evaluates to {@code true} if the object reference
071 * being tested is null.
072 */
073 @SuppressWarnings("unchecked")
074 public static <T> Predicate<T> isNull() {
075 return (Predicate<T>) IsNullPredicate.INSTANCE;
076 }
077
078 /**
079 * Returns a predicate that evaluates to {@code true} if the object reference
080 * being tested is not null.
081 */
082 @SuppressWarnings("unchecked")
083 public static <T> Predicate<T> notNull() {
084 return (Predicate<T>) NotNullPredicate.INSTANCE;
085 }
086
087 /**
088 * Returns a predicate that evaluates to {@code true} if the given predicate
089 * evaluates to {@code false}.
090 */
091 public static <T> Predicate<T> not(Predicate<T> predicate) {
092 return new NotPredicate<T>(predicate);
093 }
094
095 /**
096 * Returns a predicate that evaluates to {@code true} if each of its
097 * components evaluates to {@code true}. The components are evaluated in
098 * order, and evaluation will be "short-circuited" as soon as a false
099 * predicate is found. It defensively copies the iterable passed in, so future
100 * changes to it won't alter the behavior of this predicate. If {@code
101 * components} is empty, the returned predicate will always evaluate to {@code
102 * true}.
103 */
104 public static <T> Predicate<T> and(
105 Iterable<? extends Predicate<? super T>> components) {
106 return new AndPredicate<T>(defensiveCopy(components));
107 }
108
109 /**
110 * Returns a predicate that evaluates to {@code true} if each of its
111 * components evaluates to {@code true}. The components are evaluated in
112 * order, and evaluation will be "short-circuited" as soon as a false
113 * predicate is found. It defensively copies the array passed in, so future
114 * changes to it won't alter the behavior of this predicate. If {@code
115 * components} is empty, the returned predicate will always evaluate to {@code
116 * true}.
117 */
118 public static <T> Predicate<T> and(Predicate<? super T>... components) {
119 return new AndPredicate<T>(defensiveCopy(components));
120 }
121
122 /**
123 * Returns a predicate that evaluates to {@code true} if both of its
124 * components evaluate to {@code true}. The components are evaluated in
125 * order, and evaluation will be "short-circuited" as soon as a false
126 * predicate is found.
127 */
128 public static <T> Predicate<T> and(Predicate<? super T> first,
129 Predicate<? super T> second) {
130 return new AndPredicate<T>(Predicates.<T>asList(
131 checkNotNull(first), checkNotNull(second)));
132 }
133
134 /**
135 * Returns a predicate that evaluates to {@code true} if any one of its
136 * components evaluates to {@code true}. The components are evaluated in
137 * order, and evaluation will be "short-circuited" as soon as a
138 * true predicate is found. It defensively copies the iterable passed in, so
139 * future changes to it won't alter the behavior of this predicate. If {@code
140 * components} is empty, the returned predicate will always evaluate to {@code
141 * false}.
142 */
143 public static <T> Predicate<T> or(
144 Iterable<? extends Predicate<? super T>> components) {
145 return new OrPredicate<T>(defensiveCopy(components));
146 }
147
148 /**
149 * Returns a predicate that evaluates to {@code true} if any one of its
150 * components evaluates to {@code true}. The components are evaluated in
151 * order, and evaluation will be "short-circuited" as soon as a
152 * true predicate is found. It defensively copies the array passed in, so
153 * future changes to it won't alter the behavior of this predicate. If {@code
154 * components} is empty, the returned predicate will always evaluate to {@code
155 * false}.
156 */
157 public static <T> Predicate<T> or(Predicate<? super T>... components) {
158 return new OrPredicate<T>(defensiveCopy(components));
159 }
160
161 /**
162 * Returns a predicate that evaluates to {@code true} if either of its
163 * components evaluates to {@code true}. The components are evaluated in
164 * order, and evaluation will be "short-circuited" as soon as a
165 * true predicate is found.
166 */
167 public static <T> Predicate<T> or(
168 Predicate<? super T> first, Predicate<? super T> second) {
169 return new OrPredicate<T>(Predicates.<T>asList(
170 checkNotNull(first), checkNotNull(second)));
171 }
172
173 /**
174 * Returns a predicate that evaluates to {@code true} if the object being
175 * tested {@code equals()} the given target or both are null.
176 */
177 public static <T> Predicate<T> equalTo(@Nullable T target) {
178 return (target == null)
179 ? Predicates.<T>isNull()
180 : new IsEqualToPredicate<T>(target);
181 }
182
183 /**
184 * Returns a predicate that evaluates to {@code true} if the object being
185 * tested is an instance of the given class. If the object being tested
186 * is {@code null} this predicate evaluates to {@code false}.
187 *
188 * <p>If you want to filter an {@code Iterable} to narrow its type, consider
189 * using {@link com.google.common.collect.Iterables#filter(Iterable, Class)}
190 * in preference.
191 */
192 @GwtIncompatible("Class.isInstance")
193 public static Predicate<Object> instanceOf(Class<?> clazz) {
194 return new InstanceOfPredicate(clazz);
195 }
196
197 /**
198 * Returns a predicate that evaluates to {@code true} if the object reference
199 * being tested is a member of the given collection. It does not defensively
200 * copy the collection passed in, so future changes to it will alter the
201 * behavior of the predicate.
202 *
203 * This method can technically accept any Collection<?>, but using a typed
204 * collection helps prevent bugs. This approach doesn't block any potential
205 * users since it is always possible to use {@code Predicates.<Object>in()}.
206 *
207 * @param target the collection that may contain the function input
208 */
209 public static <T> Predicate<T> in(Collection<? extends T> target) {
210 return new InPredicate<T>(target);
211 }
212
213 /**
214 * Returns the composition of a function and a predicate. For every {@code x},
215 * the generated predicate returns {@code predicate(function(x))}.
216 *
217 * @return the composition of the provided function and predicate
218 */
219 public static <A, B> Predicate<A> compose(
220 Predicate<B> predicate, Function<A, ? extends B> function) {
221 return new CompositionPredicate<A, B>(predicate, function);
222 }
223
224 /**
225 * Returns a predicate that evaluates to {@code true} if the
226 * {@code CharSequence} being tested contains any match for the given
227 * regular expression pattern. The test used is equivalent to
228 * {@code Pattern.compile(pattern).matcher(arg).find()}
229 *
230 * @throws java.util.regex.PatternSyntaxException if the pattern is invalid
231 * @since 3
232 */
233 @Beta
234 @GwtIncompatible(value = "java.util.regex.Pattern")
235 public static Predicate<CharSequence> containsPattern(String pattern) {
236 return new ContainsPatternPredicate(pattern);
237 }
238
239 /**
240 * Returns a predicate that evaluates to {@code true} if the
241 * {@code CharSequence} being tested contains any match for the given
242 * regular expression pattern. The test used is equivalent to
243 * {@code regex.matcher(arg).find()}
244 *
245 * @since 3
246 */
247 @GwtIncompatible(value = "java.util.regex.Pattern")
248 public static Predicate<CharSequence> contains(Pattern pattern) {
249 return new ContainsPatternPredicate(pattern);
250 }
251
252 /**
253 * @see Predicates#contains(Pattern)
254 * @see Predicates#containsPattern(String)
255 */
256 private static class ContainsPatternPredicate
257 implements Predicate<CharSequence>, Serializable {
258 final Pattern pattern;
259
260 ContainsPatternPredicate(Pattern pattern) {
261 this.pattern = checkNotNull(pattern);
262 }
263
264 ContainsPatternPredicate(String patternStr) {
265 this(Pattern.compile(patternStr));
266 }
267
268 public boolean apply(CharSequence t) {
269 return pattern.matcher(t).find();
270 }
271
272 @Override public int hashCode() {
273 // Pattern uses Object.hashCode, so we have to reach
274 // inside to build a hashCode consistent with equals.
275
276 return Objects.hashCode(pattern.pattern(), pattern.flags());
277 }
278
279 @Override public boolean equals(@Nullable Object obj) {
280 if (obj instanceof ContainsPatternPredicate) {
281 ContainsPatternPredicate that = (ContainsPatternPredicate) obj;
282
283 // Pattern uses Object (identity) equality, so we have to reach
284 // inside to compare individual fields.
285 return Objects.equal(pattern.pattern(), that.pattern.pattern())
286 && Objects.equal(pattern.flags(), that.pattern.flags());
287 }
288 return false;
289 }
290
291 @Override public String toString() {
292 return Objects.toStringHelper(this)
293 .add("pattern", pattern)
294 .add("pattern.flags", Integer.toHexString(pattern.flags()))
295 .toString();
296 }
297
298 private static final long serialVersionUID = 0;
299 }
300
301 /** @see Predicates#alwaysTrue() */
302 // Package private for GWT serialization.
303 enum AlwaysTruePredicate implements Predicate<Object> {
304 INSTANCE;
305
306 public boolean apply(@Nullable Object o) {
307 return true;
308 }
309 @Override public String toString() {
310 return "AlwaysTrue";
311 }
312 }
313
314 /** @see Predicates#alwaysFalse() */
315 // Package private for GWT serialization.
316 enum AlwaysFalsePredicate implements Predicate<Object> {
317 INSTANCE;
318
319 public boolean apply(@Nullable Object o) {
320 return false;
321 }
322 @Override public String toString() {
323 return "AlwaysFalse";
324 }
325 }
326
327 /** @see Predicates#not(Predicate) */
328 private static class NotPredicate<T> implements Predicate<T>, Serializable {
329 final Predicate<T> predicate;
330
331 NotPredicate(Predicate<T> predicate) {
332 this.predicate = checkNotNull(predicate);
333 }
334 public boolean apply(T t) {
335 return !predicate.apply(t);
336 }
337 @Override public int hashCode() {
338 return ~predicate.hashCode();
339 }
340 @Override public boolean equals(@Nullable Object obj) {
341 if (obj instanceof NotPredicate) {
342 NotPredicate<?> that = (NotPredicate<?>) obj;
343 return predicate.equals(that.predicate);
344 }
345 return false;
346 }
347 @Override public String toString() {
348 return "Not(" + predicate.toString() + ")";
349 }
350 private static final long serialVersionUID = 0;
351 }
352
353 private static final Joiner commaJoiner = Joiner.on(",");
354
355 /** @see Predicates#and(Iterable) */
356 private static class AndPredicate<T> implements Predicate<T>, Serializable {
357 private final Iterable<? extends Predicate<? super T>> components;
358
359 private AndPredicate(Iterable<? extends Predicate<? super T>> components) {
360 this.components = components;
361 }
362 public boolean apply(T t) {
363 for (Predicate<? super T> predicate : components) {
364 if (!predicate.apply(t)) {
365 return false;
366 }
367 }
368 return true;
369 }
370 @Override public int hashCode() {
371 int result = -1; /* Start with all bits on. */
372 for (Predicate<? super T> predicate : components) {
373 result &= predicate.hashCode();
374 }
375 return result;
376 }
377 @Override public boolean equals(@Nullable Object obj) {
378 if (obj instanceof AndPredicate) {
379 AndPredicate<?> that = (AndPredicate<?>) obj;
380 return iterableElementsEqual(components, that.components);
381 }
382 return false;
383 }
384 @Override public String toString() {
385 return "And(" + commaJoiner.join(components) + ")";
386 }
387 private static final long serialVersionUID = 0;
388 }
389
390 /** @see Predicates#or(Iterable) */
391 private static class OrPredicate<T> implements Predicate<T>, Serializable {
392 private final Iterable<? extends Predicate<? super T>> components;
393
394 private OrPredicate(Iterable<? extends Predicate<? super T>> components) {
395 this.components = components;
396 }
397 public boolean apply(T t) {
398 for (Predicate<? super T> predicate : components) {
399 if (predicate.apply(t)) {
400 return true;
401 }
402 }
403 return false;
404 }
405 @Override public int hashCode() {
406 int result = 0; /* Start with all bits off. */
407 for (Predicate<? super T> predicate : components) {
408 result |= predicate.hashCode();
409 }
410 return result;
411 }
412 @Override public boolean equals(@Nullable Object obj) {
413 if (obj instanceof OrPredicate) {
414 OrPredicate<?> that = (OrPredicate<?>) obj;
415 return iterableElementsEqual(components, that.components);
416 }
417 return false;
418 }
419 @Override public String toString() {
420 return "Or(" + commaJoiner.join(components) + ")";
421 }
422 private static final long serialVersionUID = 0;
423 }
424
425 /** @see Predicates#equalTo(Object) */
426 private static class IsEqualToPredicate<T>
427 implements Predicate<T>, Serializable {
428 private final T target;
429
430 private IsEqualToPredicate(T target) {
431 this.target = target;
432 }
433 public boolean apply(T t) {
434 return target.equals(t);
435 }
436 @Override public int hashCode() {
437 return target.hashCode();
438 }
439 @Override public boolean equals(@Nullable Object obj) {
440 if (obj instanceof IsEqualToPredicate) {
441 IsEqualToPredicate<?> that = (IsEqualToPredicate<?>) obj;
442 return target.equals(that.target);
443 }
444 return false;
445 }
446 @Override public String toString() {
447 return "IsEqualTo(" + target + ")";
448 }
449 private static final long serialVersionUID = 0;
450 }
451
452 /** @see Predicates#instanceOf(Class) */
453 private static class InstanceOfPredicate
454 implements Predicate<Object>, Serializable {
455 private final Class<?> clazz;
456
457 private InstanceOfPredicate(Class<?> clazz) {
458 this.clazz = checkNotNull(clazz);
459 }
460 public boolean apply(@Nullable Object o) {
461 return Platform.isInstance(clazz, o);
462 }
463 @Override public int hashCode() {
464 return clazz.hashCode();
465 }
466 @Override public boolean equals(@Nullable Object obj) {
467 if (obj instanceof InstanceOfPredicate) {
468 InstanceOfPredicate that = (InstanceOfPredicate) obj;
469 return clazz == that.clazz;
470 }
471 return false;
472 }
473 @Override public String toString() {
474 return "IsInstanceOf(" + clazz.getName() + ")";
475 }
476 private static final long serialVersionUID = 0;
477 }
478
479 /** @see Predicates#isNull() */
480 // enum singleton pattern
481 private enum IsNullPredicate implements Predicate<Object> {
482 INSTANCE;
483
484 public boolean apply(@Nullable Object o) {
485 return o == null;
486 }
487 @Override public String toString() {
488 return "IsNull";
489 }
490 }
491
492 /** @see Predicates#notNull() */
493 // enum singleton pattern
494 private enum NotNullPredicate implements Predicate<Object> {
495 INSTANCE;
496
497 public boolean apply(@Nullable Object o) {
498 return o != null;
499 }
500 @Override public String toString() {
501 return "NotNull";
502 }
503 }
504
505 /** @see Predicates#in(Collection) */
506 private static class InPredicate<T> implements Predicate<T>, Serializable {
507 private final Collection<?> target;
508
509 private InPredicate(Collection<?> target) {
510 this.target = checkNotNull(target);
511 }
512
513 public boolean apply(T t) {
514 try {
515 return target.contains(t);
516 } catch (NullPointerException e) {
517 return false;
518 } catch (ClassCastException e) {
519 return false;
520 }
521 }
522
523 @Override public boolean equals(@Nullable Object obj) {
524 if (obj instanceof InPredicate) {
525 InPredicate<?> that = (InPredicate<?>) obj;
526 return target.equals(that.target);
527 }
528 return false;
529 }
530
531 @Override public int hashCode() {
532 return target.hashCode();
533 }
534
535 @Override public String toString() {
536 return "In(" + target + ")";
537 }
538 private static final long serialVersionUID = 0;
539 }
540
541 /** @see Predicates#compose(Predicate, Function) */
542 private static class CompositionPredicate<A, B>
543 implements Predicate<A>, Serializable {
544 final Predicate<B> p;
545 final Function<A, ? extends B> f;
546
547 private CompositionPredicate(Predicate<B> p, Function<A, ? extends B> f) {
548 this.p = checkNotNull(p);
549 this.f = checkNotNull(f);
550 }
551
552 public boolean apply(A a) {
553 return p.apply(f.apply(a));
554 }
555
556 @Override public boolean equals(@Nullable Object obj) {
557 if (obj instanceof CompositionPredicate) {
558 CompositionPredicate<?, ?> that = (CompositionPredicate<?, ?>) obj;
559 return f.equals(that.f) && p.equals(that.p);
560 }
561 return false;
562 }
563
564 @Override public int hashCode() {
565 /*
566 * TODO: To leave the door open for future enhancement, this
567 * calculation should be coordinated with the hashCode() method of the
568 * corresponding composition method in Functions. To construct the
569 * composition:
570 * predicate(function2(function1(x)))
571 *
572 * There are two different ways of composing it:
573 * compose(predicate, compose(function2, function1))
574 * compose(compose(predicate, function2), function1)
575 *
576 * It would be nice if these could be equal.
577 */
578 return f.hashCode() ^ p.hashCode();
579 }
580
581 @Override public String toString() {
582 return p.toString() + "(" + f.toString() + ")";
583 }
584
585 private static final long serialVersionUID = 0;
586 }
587
588 /**
589 * Determines whether the two Iterables contain equal elements. More
590 * specifically, this method returns {@code true} if {@code iterable1} and
591 * {@code iterable2} contain the same number of elements and every element of
592 * {@code iterable1} is equal to the corresponding element of {@code
593 * iterable2}.
594 *
595 * <p>This is not a general-purpose method; it assumes that the iterations
596 * contain no {@code null} elements.
597 */
598 private static boolean iterableElementsEqual(
599 Iterable<?> iterable1, Iterable<?> iterable2) {
600 Iterator<?> iterator1 = iterable1.iterator();
601 Iterator<?> iterator2 = iterable2.iterator();
602 while (iterator1.hasNext()) {
603 if (!iterator2.hasNext()) {
604 return false;
605 }
606 if (!iterator1.next().equals(iterator2.next())) {
607 return false;
608 }
609 }
610 return !iterator2.hasNext();
611 }
612
613 @SuppressWarnings("unchecked")
614 private static <T> List<Predicate<? super T>> asList(
615 Predicate<? super T> first, Predicate<? super T> second) {
616 return Arrays.<Predicate<? super T>>asList(first, second);
617 }
618
619 private static <T> List<T> defensiveCopy(T... array) {
620 return defensiveCopy(Arrays.asList(array));
621 }
622
623 static <T> List<T> defensiveCopy(Iterable<T> iterable) {
624 ArrayList<T> list = new ArrayList<T>();
625 for (T element : iterable) {
626 list.add(checkNotNull(element));
627 }
628 return list;
629 }
630 }