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