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