001/* 002 * Copyright (C) 2007 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 005 * in compliance with the License. You may obtain a copy of the License at 006 * 007 * http://www.apache.org/licenses/LICENSE-2.0 008 * 009 * Unless required by applicable law or agreed to in writing, software distributed under the License 010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 011 * or implied. See the License for the specific language governing permissions and limitations under 012 * the License. 013 */ 014 015package com.google.common.base; 016 017import static com.google.common.base.Preconditions.checkNotNull; 018 019import com.google.common.annotations.Beta; 020import com.google.common.annotations.GwtCompatible; 021import com.google.common.annotations.GwtIncompatible; 022import java.io.Serializable; 023import java.util.ArrayList; 024import java.util.Arrays; 025import java.util.Collection; 026import java.util.List; 027import java.util.regex.Pattern; 028import javax.annotation.Nullable; 029 030/** 031 * Static utility methods pertaining to {@code Predicate} instances. 032 * 033 * <p>All methods return serializable predicates as long as they're given serializable parameters. 034 * 035 * <p>See the Guava User Guide article on 036 * <a href="https://github.com/google/guava/wiki/FunctionalExplained">the use of 037 * {@code Predicate}</a>. 038 * 039 * @author Kevin Bourrillion 040 * @since 2.0 041 */ 042@GwtCompatible(emulated = true) 043public final class Predicates { 044 private Predicates() {} 045 046 // TODO(kevinb): considering having these implement a VisitablePredicate 047 // interface which specifies an accept(PredicateVisitor) method. 048 049 /** 050 * Returns a predicate that always evaluates to {@code true}. 051 */ 052 @GwtCompatible(serializable = true) 053 public static <T> Predicate<T> alwaysTrue() { 054 return ObjectPredicate.ALWAYS_TRUE.withNarrowedType(); 055 } 056 057 /** 058 * Returns a predicate that always evaluates to {@code false}. 059 */ 060 @GwtCompatible(serializable = true) 061 public static <T> Predicate<T> alwaysFalse() { 062 return ObjectPredicate.ALWAYS_FALSE.withNarrowedType(); 063 } 064 065 /** 066 * Returns a predicate that evaluates to {@code true} if the object reference being tested is 067 * null. 068 */ 069 @GwtCompatible(serializable = true) 070 public static <T> Predicate<T> isNull() { 071 return ObjectPredicate.IS_NULL.withNarrowedType(); 072 } 073 074 /** 075 * Returns a predicate that evaluates to {@code true} if the object reference being tested is not 076 * null. 077 */ 078 @GwtCompatible(serializable = true) 079 public static <T> Predicate<T> notNull() { 080 return ObjectPredicate.NOT_NULL.withNarrowedType(); 081 } 082 083 /** 084 * Returns a predicate that evaluates to {@code true} if the given predicate evaluates to 085 * {@code false}. 086 */ 087 public static <T> Predicate<T> not(Predicate<T> predicate) { 088 return new NotPredicate<T>(predicate); 089 } 090 091 /** 092 * Returns a predicate that evaluates to {@code true} if each of its components evaluates to 093 * {@code true}. The components are evaluated in order, and evaluation will be "short-circuited" 094 * as soon as a false predicate is found. It defensively copies the iterable passed in, so future 095 * changes to it won't alter the behavior of this predicate. If {@code 096 * components} is empty, the returned predicate will always evaluate to {@code 097 * true}. 098 */ 099 public static <T> Predicate<T> and(Iterable<? extends Predicate<? super T>> components) { 100 return new AndPredicate<T>(defensiveCopy(components)); 101 } 102 103 /** 104 * Returns a predicate that evaluates to {@code true} if each of its components evaluates to 105 * {@code true}. The components are evaluated in order, and evaluation will be "short-circuited" 106 * as soon as a false predicate is found. It defensively copies the array passed in, so future 107 * changes to it won't alter the behavior of this predicate. If {@code 108 * components} is empty, the returned predicate will always evaluate to {@code 109 * true}. 110 */ 111 @SafeVarargs 112 public static <T> Predicate<T> and(Predicate<? super T>... components) { 113 return new AndPredicate<T>(defensiveCopy(components)); 114 } 115 116 /** 117 * Returns a predicate that evaluates to {@code true} if both of its components evaluate to 118 * {@code true}. The components are evaluated in order, and evaluation will be "short-circuited" 119 * as soon as a false predicate is found. 120 */ 121 public static <T> Predicate<T> and(Predicate<? super T> first, Predicate<? super T> second) { 122 return new AndPredicate<T>(Predicates.<T>asList(checkNotNull(first), checkNotNull(second))); 123 } 124 125 /** 126 * Returns a predicate that evaluates to {@code true} if any one of its components evaluates to 127 * {@code true}. The components are evaluated in order, and evaluation will be "short-circuited" 128 * as soon as a true predicate is found. It defensively copies the iterable passed in, so future 129 * changes to it won't alter the behavior of this predicate. If {@code 130 * components} is empty, the returned predicate will always evaluate to {@code 131 * false}. 132 */ 133 public static <T> Predicate<T> or(Iterable<? extends Predicate<? super T>> components) { 134 return new OrPredicate<T>(defensiveCopy(components)); 135 } 136 137 /** 138 * Returns a predicate that evaluates to {@code true} if any one of its components evaluates to 139 * {@code true}. The components are evaluated in order, and evaluation will be "short-circuited" 140 * as soon as a true predicate is found. It defensively copies the array passed in, so future 141 * changes to it won't alter the behavior of this predicate. If {@code 142 * components} is empty, the returned predicate will always evaluate to {@code 143 * false}. 144 */ 145 @SafeVarargs 146 public static <T> Predicate<T> or(Predicate<? super T>... components) { 147 return new OrPredicate<T>(defensiveCopy(components)); 148 } 149 150 /** 151 * Returns a predicate that evaluates to {@code true} if either of its components evaluates to 152 * {@code true}. The components are evaluated in order, and evaluation will be "short-circuited" 153 * as soon as a true predicate is found. 154 */ 155 public static <T> Predicate<T> or(Predicate<? super T> first, Predicate<? super T> second) { 156 return new OrPredicate<T>(Predicates.<T>asList(checkNotNull(first), checkNotNull(second))); 157 } 158 159 /** 160 * Returns a predicate that evaluates to {@code true} if the object being tested {@code equals()} 161 * the given target or both are null. 162 */ 163 public static <T> Predicate<T> equalTo(@Nullable T target) { 164 return (target == null) ? Predicates.<T>isNull() : new IsEqualToPredicate<T>(target); 165 } 166 167 /** 168 * Returns a predicate that evaluates to {@code true} if the object being tested is an instance of 169 * the given class. If the object being tested is {@code null} this predicate evaluates to 170 * {@code false}. 171 * 172 * <p>If you want to filter an {@code Iterable} to narrow its type, consider using 173 * {@link com.google.common.collect.Iterables#filter(Iterable, Class)} in preference. 174 * 175 * <p><b>Warning:</b> contrary to the typical assumptions about predicates (as documented at 176 * {@link Predicate#apply}), the returned predicate may not be <i>consistent with equals</i>. For 177 * example, {@code instanceOf(ArrayList.class)} will yield different results for the two equal 178 * instances {@code Lists.newArrayList(1)} and {@code Arrays.asList(1)}. 179 */ 180 @GwtIncompatible // Class.isInstance 181 public static Predicate<Object> instanceOf(Class<?> clazz) { 182 return new InstanceOfPredicate(clazz); 183 } 184 185 /** 186 * Returns a predicate that evaluates to {@code true} if the class being tested is assignable 187 * <b>TO</b> {@code clazz}, that is, if it is a <b>subtype</b> of {@code clazz}. Yes, this method 188 * is named very incorrectly! Example: <pre> {@code 189 * 190 * List<Class<?>> classes = Arrays.asList( 191 * Object.class, String.class, Number.class, Long.class); 192 * return Iterables.filter(classes, assignableFrom(Number.class));}</pre> 193 * 194 * The code above returns {@code Number.class} and {@code Long.class}, <b>not</b> {@code 195 * Number.class} and {@code Object.class} as the name implies! 196 * 197 * <p>The returned predicate does not allow null inputs. 198 * 199 * @deprecated Use the correctly-named method {@link #subtypeOf} instead. 200 * @since 10.0 201 */ 202 @GwtIncompatible // Class.isAssignableFrom 203 @Beta 204 @Deprecated 205 public static Predicate<Class<?>> assignableFrom(Class<?> clazz) { 206 return subtypeOf(clazz); 207 } 208 209 /** 210 * Returns a predicate that evaluates to {@code true} if the class being tested is assignable 211 * to (is a subtype of) {@code clazz}. Example: <pre> {@code 212 * 213 * List<Class<?>> classes = Arrays.asList( 214 * Object.class, String.class, Number.class, Long.class); 215 * return Iterables.filter(classes, subtypeOf(Number.class));}</pre> 216 * 217 * The code above returns an iterable containing {@code Number.class} and {@code Long.class}. 218 * 219 * @since 20.0 (since 10.0 under the incorrect name {@code assignableFrom}) 220 */ 221 @GwtIncompatible // Class.isAssignableFrom 222 @Beta 223 public static Predicate<Class<?>> subtypeOf(Class<?> clazz) { 224 return new SubtypeOfPredicate(clazz); 225 } 226 227 /** 228 * Returns a predicate that evaluates to {@code true} if the object reference being tested is a 229 * member of the given collection. It does not defensively copy the collection passed in, so 230 * future changes to it will alter the behavior of the predicate. 231 * 232 * <p>This method can technically accept any {@code Collection<?>}, but using a typed collection 233 * helps prevent bugs. This approach doesn't block any potential users since it is always possible 234 * to use {@code Predicates.<Object>in()}. 235 * 236 * @param target the collection that may contain the function input 237 */ 238 public static <T> Predicate<T> in(Collection<? extends T> target) { 239 return new InPredicate<T>(target); 240 } 241 242 /** 243 * Returns the composition of a function and a predicate. For every {@code x}, the generated 244 * predicate returns {@code predicate(function(x))}. 245 * 246 * @return the composition of the provided function and predicate 247 */ 248 public static <A, B> Predicate<A> compose( 249 Predicate<B> predicate, Function<A, ? extends B> function) { 250 return new CompositionPredicate<>(predicate, function); 251 } 252 253 /** 254 * Returns a predicate that evaluates to {@code true} if the {@code CharSequence} being tested 255 * contains any match for the given regular expression pattern. The test used is equivalent to 256 * {@code Pattern.compile(pattern).matcher(arg).find()} 257 * 258 * @throws IllegalArgumentException if the pattern is invalid 259 * @since 3.0 260 */ 261 @GwtIncompatible // Only used by other GWT-incompatible code. 262 public static Predicate<CharSequence> containsPattern(String pattern) { 263 return new ContainsPatternFromStringPredicate(pattern); 264 } 265 266 /** 267 * Returns a predicate that evaluates to {@code true} if the {@code CharSequence} being tested 268 * contains any match for the given regular expression pattern. The test used is equivalent to 269 * {@code pattern.matcher(arg).find()} 270 * 271 * @since 3.0 272 */ 273 @GwtIncompatible(value = "java.util.regex.Pattern") 274 public static Predicate<CharSequence> contains(Pattern pattern) { 275 return new ContainsPatternPredicate(new JdkPattern(pattern)); 276 } 277 278 // End public API, begin private implementation classes. 279 280 // Package private for GWT serialization. 281 enum ObjectPredicate implements Predicate<Object> { 282 /** @see Predicates#alwaysTrue() */ 283 ALWAYS_TRUE { 284 @Override 285 public boolean apply(@Nullable Object o) { 286 return true; 287 } 288 289 @Override 290 public String toString() { 291 return "Predicates.alwaysTrue()"; 292 } 293 }, 294 /** @see Predicates#alwaysFalse() */ 295 ALWAYS_FALSE { 296 @Override 297 public boolean apply(@Nullable Object o) { 298 return false; 299 } 300 301 @Override 302 public String toString() { 303 return "Predicates.alwaysFalse()"; 304 } 305 }, 306 /** @see Predicates#isNull() */ 307 IS_NULL { 308 @Override 309 public boolean apply(@Nullable Object o) { 310 return o == null; 311 } 312 313 @Override 314 public String toString() { 315 return "Predicates.isNull()"; 316 } 317 }, 318 /** @see Predicates#notNull() */ 319 NOT_NULL { 320 @Override 321 public boolean apply(@Nullable Object o) { 322 return o != null; 323 } 324 325 @Override 326 public String toString() { 327 return "Predicates.notNull()"; 328 } 329 }; 330 331 @SuppressWarnings("unchecked") // safe contravariant cast 332 <T> Predicate<T> withNarrowedType() { 333 return (Predicate<T>) this; 334 } 335 } 336 337 /** @see Predicates#not(Predicate) */ 338 private static class NotPredicate<T> implements Predicate<T>, Serializable { 339 final Predicate<T> predicate; 340 341 NotPredicate(Predicate<T> predicate) { 342 this.predicate = checkNotNull(predicate); 343 } 344 345 @Override 346 public boolean apply(@Nullable T t) { 347 return !predicate.apply(t); 348 } 349 350 @Override 351 public int hashCode() { 352 return ~predicate.hashCode(); 353 } 354 355 @Override 356 public boolean equals(@Nullable Object obj) { 357 if (obj instanceof NotPredicate) { 358 NotPredicate<?> that = (NotPredicate<?>) obj; 359 return predicate.equals(that.predicate); 360 } 361 return false; 362 } 363 364 @Override 365 public String toString() { 366 return "Predicates.not(" + predicate + ")"; 367 } 368 369 private static final long serialVersionUID = 0; 370 } 371 372 /** @see Predicates#and(Iterable) */ 373 private static class AndPredicate<T> implements Predicate<T>, Serializable { 374 private final List<? extends Predicate<? super T>> components; 375 376 private AndPredicate(List<? extends Predicate<? super T>> components) { 377 this.components = components; 378 } 379 380 @Override 381 public boolean apply(@Nullable T t) { 382 // Avoid using the Iterator to avoid generating garbage (issue 820). 383 for (int i = 0; i < components.size(); i++) { 384 if (!components.get(i).apply(t)) { 385 return false; 386 } 387 } 388 return true; 389 } 390 391 @Override 392 public int hashCode() { 393 // add a random number to avoid collisions with OrPredicate 394 return components.hashCode() + 0x12472c2c; 395 } 396 397 @Override 398 public boolean equals(@Nullable Object obj) { 399 if (obj instanceof AndPredicate) { 400 AndPredicate<?> that = (AndPredicate<?>) obj; 401 return components.equals(that.components); 402 } 403 return false; 404 } 405 406 @Override 407 public String toString() { 408 return toStringHelper("and", components); 409 } 410 411 private static final long serialVersionUID = 0; 412 } 413 414 /** @see Predicates#or(Iterable) */ 415 private static class OrPredicate<T> implements Predicate<T>, Serializable { 416 private final List<? extends Predicate<? super T>> components; 417 418 private OrPredicate(List<? extends Predicate<? super T>> components) { 419 this.components = components; 420 } 421 422 @Override 423 public boolean apply(@Nullable T t) { 424 // Avoid using the Iterator to avoid generating garbage (issue 820). 425 for (int i = 0; i < components.size(); i++) { 426 if (components.get(i).apply(t)) { 427 return true; 428 } 429 } 430 return false; 431 } 432 433 @Override 434 public int hashCode() { 435 // add a random number to avoid collisions with AndPredicate 436 return components.hashCode() + 0x053c91cf; 437 } 438 439 @Override 440 public boolean equals(@Nullable Object obj) { 441 if (obj instanceof OrPredicate) { 442 OrPredicate<?> that = (OrPredicate<?>) obj; 443 return components.equals(that.components); 444 } 445 return false; 446 } 447 448 @Override 449 public String toString() { 450 return toStringHelper("or", components); 451 } 452 453 private static final long serialVersionUID = 0; 454 } 455 456 private static String toStringHelper(String methodName, Iterable<?> components) { 457 StringBuilder builder = new StringBuilder("Predicates.").append(methodName).append('('); 458 boolean first = true; 459 for (Object o : components) { 460 if (!first) { 461 builder.append(','); 462 } 463 builder.append(o); 464 first = false; 465 } 466 return builder.append(')').toString(); 467 } 468 469 /** @see Predicates#equalTo(Object) */ 470 private static class IsEqualToPredicate<T> implements Predicate<T>, Serializable { 471 private final T target; 472 473 private IsEqualToPredicate(T target) { 474 this.target = target; 475 } 476 477 @Override 478 public boolean apply(T t) { 479 return target.equals(t); 480 } 481 482 @Override 483 public int hashCode() { 484 return target.hashCode(); 485 } 486 487 @Override 488 public boolean equals(@Nullable Object obj) { 489 if (obj instanceof IsEqualToPredicate) { 490 IsEqualToPredicate<?> that = (IsEqualToPredicate<?>) obj; 491 return target.equals(that.target); 492 } 493 return false; 494 } 495 496 @Override 497 public String toString() { 498 return "Predicates.equalTo(" + target + ")"; 499 } 500 501 private static final long serialVersionUID = 0; 502 } 503 504 /** @see Predicates#instanceOf(Class) */ 505 @GwtIncompatible // Class.isInstance 506 private static class InstanceOfPredicate implements Predicate<Object>, Serializable { 507 private final Class<?> clazz; 508 509 private InstanceOfPredicate(Class<?> clazz) { 510 this.clazz = checkNotNull(clazz); 511 } 512 513 @Override 514 public boolean apply(@Nullable Object o) { 515 return clazz.isInstance(o); 516 } 517 518 @Override 519 public int hashCode() { 520 return clazz.hashCode(); 521 } 522 523 @Override 524 public boolean equals(@Nullable Object obj) { 525 if (obj instanceof InstanceOfPredicate) { 526 InstanceOfPredicate that = (InstanceOfPredicate) obj; 527 return clazz == that.clazz; 528 } 529 return false; 530 } 531 532 @Override 533 public String toString() { 534 return "Predicates.instanceOf(" + clazz.getName() + ")"; 535 } 536 537 private static final long serialVersionUID = 0; 538 } 539 540 /** @see Predicates#subtypeOf(Class) */ 541 @GwtIncompatible // Class.isAssignableFrom 542 private static class SubtypeOfPredicate implements Predicate<Class<?>>, Serializable { 543 private final Class<?> clazz; 544 545 private SubtypeOfPredicate(Class<?> clazz) { 546 this.clazz = checkNotNull(clazz); 547 } 548 549 @Override 550 public boolean apply(Class<?> input) { 551 return clazz.isAssignableFrom(input); 552 } 553 554 @Override 555 public int hashCode() { 556 return clazz.hashCode(); 557 } 558 559 @Override 560 public boolean equals(@Nullable Object obj) { 561 if (obj instanceof SubtypeOfPredicate) { 562 SubtypeOfPredicate that = (SubtypeOfPredicate) obj; 563 return clazz == that.clazz; 564 } 565 return false; 566 } 567 568 @Override 569 public String toString() { 570 return "Predicates.subtypeOf(" + clazz.getName() + ")"; 571 } 572 573 private static final long serialVersionUID = 0; 574 } 575 576 /** @see Predicates#in(Collection) */ 577 private static class InPredicate<T> implements Predicate<T>, Serializable { 578 private final Collection<?> target; 579 580 private InPredicate(Collection<?> target) { 581 this.target = checkNotNull(target); 582 } 583 584 @Override 585 public boolean apply(@Nullable T t) { 586 try { 587 return target.contains(t); 588 } catch (NullPointerException | ClassCastException e) { 589 return false; 590 } 591 } 592 593 @Override 594 public boolean equals(@Nullable Object obj) { 595 if (obj instanceof InPredicate) { 596 InPredicate<?> that = (InPredicate<?>) obj; 597 return target.equals(that.target); 598 } 599 return false; 600 } 601 602 @Override 603 public int hashCode() { 604 return target.hashCode(); 605 } 606 607 @Override 608 public String toString() { 609 return "Predicates.in(" + target + ")"; 610 } 611 612 private static final long serialVersionUID = 0; 613 } 614 615 /** @see Predicates#compose(Predicate, Function) */ 616 private static class CompositionPredicate<A, B> implements Predicate<A>, Serializable { 617 final Predicate<B> p; 618 final Function<A, ? extends B> f; 619 620 private CompositionPredicate(Predicate<B> p, Function<A, ? extends B> f) { 621 this.p = checkNotNull(p); 622 this.f = checkNotNull(f); 623 } 624 625 @Override 626 public boolean apply(@Nullable A a) { 627 return p.apply(f.apply(a)); 628 } 629 630 @Override 631 public boolean equals(@Nullable Object obj) { 632 if (obj instanceof CompositionPredicate) { 633 CompositionPredicate<?, ?> that = (CompositionPredicate<?, ?>) obj; 634 return f.equals(that.f) && p.equals(that.p); 635 } 636 return false; 637 } 638 639 @Override 640 public int hashCode() { 641 return f.hashCode() ^ p.hashCode(); 642 } 643 644 @Override 645 public String toString() { 646 // TODO(cpovirk): maybe make this look like the method call does ("Predicates.compose(...)") 647 return p + "(" + f + ")"; 648 } 649 650 private static final long serialVersionUID = 0; 651 } 652 653 /** @see Predicates#contains(Pattern) */ 654 @GwtIncompatible // Only used by other GWT-incompatible code. 655 private static class ContainsPatternPredicate implements Predicate<CharSequence>, Serializable { 656 final CommonPattern pattern; 657 658 ContainsPatternPredicate(CommonPattern pattern) { 659 this.pattern = checkNotNull(pattern); 660 } 661 662 @Override 663 public boolean apply(CharSequence t) { 664 return pattern.matcher(t).find(); 665 } 666 667 @Override 668 public int hashCode() { 669 // Pattern uses Object.hashCode, so we have to reach 670 // inside to build a hashCode consistent with equals. 671 672 return Objects.hashCode(pattern.pattern(), pattern.flags()); 673 } 674 675 @Override 676 public boolean equals(@Nullable Object obj) { 677 if (obj instanceof ContainsPatternPredicate) { 678 ContainsPatternPredicate that = (ContainsPatternPredicate) obj; 679 680 // Pattern uses Object (identity) equality, so we have to reach 681 // inside to compare individual fields. 682 return Objects.equal(pattern.pattern(), that.pattern.pattern()) 683 && pattern.flags() == that.pattern.flags(); 684 } 685 return false; 686 } 687 688 @Override 689 public String toString() { 690 String patternString = 691 MoreObjects.toStringHelper(pattern) 692 .add("pattern", pattern.pattern()) 693 .add("pattern.flags", pattern.flags()) 694 .toString(); 695 return "Predicates.contains(" + patternString + ")"; 696 } 697 698 private static final long serialVersionUID = 0; 699 } 700 701 /** @see Predicates#containsPattern(String) */ 702 @GwtIncompatible // Only used by other GWT-incompatible code. 703 private static class ContainsPatternFromStringPredicate extends ContainsPatternPredicate { 704 705 ContainsPatternFromStringPredicate(String string) { 706 super(Platform.compilePattern(string)); 707 } 708 709 @Override 710 public String toString() { 711 return "Predicates.containsPattern(" + pattern.pattern() + ")"; 712 } 713 714 private static final long serialVersionUID = 0; 715 } 716 717 private static <T> List<Predicate<? super T>> asList( 718 Predicate<? super T> first, Predicate<? super T> second) { 719 // TODO(kevinb): understand why we still get a warning despite @SafeVarargs! 720 return Arrays.<Predicate<? super T>>asList(first, second); 721 } 722 723 private static <T> List<T> defensiveCopy(T... array) { 724 return defensiveCopy(Arrays.asList(array)); 725 } 726 727 static <T> List<T> defensiveCopy(Iterable<T> iterable) { 728 ArrayList<T> list = new ArrayList<T>(); 729 for (T element : iterable) { 730 list.add(checkNotNull(element)); 731 } 732 return list; 733 } 734}