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 /** @see Predicates#alwaysTrue() */ 258 ALWAYS_TRUE { 259 @Override 260 public boolean apply(@Nullable Object o) { 261 return true; 262 } 263 264 @Override 265 public String toString() { 266 return "Predicates.alwaysTrue()"; 267 } 268 }, 269 /** @see Predicates#alwaysFalse() */ 270 ALWAYS_FALSE { 271 @Override 272 public boolean apply(@Nullable Object o) { 273 return false; 274 } 275 276 @Override 277 public String toString() { 278 return "Predicates.alwaysFalse()"; 279 } 280 }, 281 /** @see Predicates#isNull() */ 282 IS_NULL { 283 @Override 284 public boolean apply(@Nullable Object o) { 285 return o == null; 286 } 287 288 @Override 289 public String toString() { 290 return "Predicates.isNull()"; 291 } 292 }, 293 /** @see Predicates#notNull() */ 294 NOT_NULL { 295 @Override 296 public boolean apply(@Nullable Object o) { 297 return o != null; 298 } 299 300 @Override 301 public String toString() { 302 return "Predicates.notNull()"; 303 } 304 }; 305 306 @SuppressWarnings("unchecked") // safe contravariant cast 307 <T extends @Nullable Object> Predicate<T> withNarrowedType() { 308 return (Predicate<T>) this; 309 } 310 } 311 312 /** @see Predicates#not(Predicate) */ 313 private static class NotPredicate<T extends @Nullable Object> 314 implements Predicate<T>, Serializable { 315 final Predicate<T> predicate; 316 317 NotPredicate(Predicate<T> predicate) { 318 this.predicate = checkNotNull(predicate); 319 } 320 321 @Override 322 public boolean apply(@ParametricNullness T t) { 323 return !predicate.apply(t); 324 } 325 326 @Override 327 public int hashCode() { 328 return ~predicate.hashCode(); 329 } 330 331 @Override 332 public boolean equals(@Nullable Object obj) { 333 if (obj instanceof NotPredicate) { 334 NotPredicate<?> that = (NotPredicate<?>) obj; 335 return predicate.equals(that.predicate); 336 } 337 return false; 338 } 339 340 @Override 341 public String toString() { 342 return "Predicates.not(" + predicate + ")"; 343 } 344 345 private static final long serialVersionUID = 0; 346 } 347 348 /** @see Predicates#and(Iterable) */ 349 private static class AndPredicate<T extends @Nullable Object> 350 implements Predicate<T>, Serializable { 351 private final List<? extends Predicate<? super T>> components; 352 353 private AndPredicate(List<? extends Predicate<? super T>> components) { 354 this.components = components; 355 } 356 357 @Override 358 public boolean apply(@ParametricNullness T t) { 359 // Avoid using the Iterator to avoid generating garbage (issue 820). 360 for (int i = 0; i < components.size(); i++) { 361 if (!components.get(i).apply(t)) { 362 return false; 363 } 364 } 365 return true; 366 } 367 368 @Override 369 public int hashCode() { 370 // add a random number to avoid collisions with OrPredicate 371 return components.hashCode() + 0x12472c2c; 372 } 373 374 @Override 375 public boolean equals(@Nullable Object obj) { 376 if (obj instanceof AndPredicate) { 377 AndPredicate<?> that = (AndPredicate<?>) obj; 378 return components.equals(that.components); 379 } 380 return false; 381 } 382 383 @Override 384 public String toString() { 385 return toStringHelper("and", components); 386 } 387 388 private static final long serialVersionUID = 0; 389 } 390 391 /** @see Predicates#or(Iterable) */ 392 private static class OrPredicate<T extends @Nullable Object> 393 implements Predicate<T>, Serializable { 394 private final List<? extends Predicate<? super T>> components; 395 396 private OrPredicate(List<? extends Predicate<? super T>> components) { 397 this.components = components; 398 } 399 400 @Override 401 public boolean apply(@ParametricNullness T t) { 402 // Avoid using the Iterator to avoid generating garbage (issue 820). 403 for (int i = 0; i < components.size(); i++) { 404 if (components.get(i).apply(t)) { 405 return true; 406 } 407 } 408 return false; 409 } 410 411 @Override 412 public int hashCode() { 413 // add a random number to avoid collisions with AndPredicate 414 return components.hashCode() + 0x053c91cf; 415 } 416 417 @Override 418 public boolean equals(@Nullable Object obj) { 419 if (obj instanceof OrPredicate) { 420 OrPredicate<?> that = (OrPredicate<?>) obj; 421 return components.equals(that.components); 422 } 423 return false; 424 } 425 426 @Override 427 public String toString() { 428 return toStringHelper("or", components); 429 } 430 431 private static final long serialVersionUID = 0; 432 } 433 434 private static String toStringHelper(String methodName, Iterable<?> components) { 435 StringBuilder builder = new StringBuilder("Predicates.").append(methodName).append('('); 436 boolean first = true; 437 for (Object o : components) { 438 if (!first) { 439 builder.append(','); 440 } 441 builder.append(o); 442 first = false; 443 } 444 return builder.append(')').toString(); 445 } 446 447 /** @see Predicates#equalTo(Object) */ 448 private static class IsEqualToPredicate implements Predicate<@Nullable Object>, Serializable { 449 private final Object target; 450 451 private IsEqualToPredicate(Object target) { 452 this.target = target; 453 } 454 455 @Override 456 public boolean apply(@Nullable Object o) { 457 return target.equals(o); 458 } 459 460 @Override 461 public int hashCode() { 462 return target.hashCode(); 463 } 464 465 @Override 466 public boolean equals(@Nullable Object obj) { 467 if (obj instanceof IsEqualToPredicate) { 468 IsEqualToPredicate that = (IsEqualToPredicate) obj; 469 return target.equals(that.target); 470 } 471 return false; 472 } 473 474 @Override 475 public String toString() { 476 return "Predicates.equalTo(" + target + ")"; 477 } 478 479 private static final long serialVersionUID = 0; 480 481 @SuppressWarnings("unchecked") // safe contravariant cast 482 <T extends @Nullable Object> Predicate<T> withNarrowedType() { 483 return (Predicate<T>) this; 484 } 485 } 486 487 /** 488 * @see Predicates#instanceOf(Class) 489 */ 490 @GwtIncompatible // Class.isInstance 491 private static class InstanceOfPredicate<T extends @Nullable Object> 492 implements Predicate<T>, Serializable { 493 private final Class<?> clazz; 494 495 private InstanceOfPredicate(Class<?> clazz) { 496 this.clazz = checkNotNull(clazz); 497 } 498 499 @Override 500 public boolean apply(@ParametricNullness T o) { 501 return clazz.isInstance(o); 502 } 503 504 @Override 505 public int hashCode() { 506 return clazz.hashCode(); 507 } 508 509 @Override 510 public boolean equals(@Nullable Object obj) { 511 if (obj instanceof InstanceOfPredicate) { 512 InstanceOfPredicate<?> that = (InstanceOfPredicate<?>) obj; 513 return clazz == that.clazz; 514 } 515 return false; 516 } 517 518 @Override 519 public String toString() { 520 return "Predicates.instanceOf(" + clazz.getName() + ")"; 521 } 522 523 @J2ktIncompatible private static final long serialVersionUID = 0; 524 } 525 526 /** 527 * @see Predicates#subtypeOf(Class) 528 */ 529 @J2ktIncompatible 530 @GwtIncompatible // Class.isAssignableFrom 531 private static class SubtypeOfPredicate implements Predicate<Class<?>>, Serializable { 532 private final Class<?> clazz; 533 534 private SubtypeOfPredicate(Class<?> clazz) { 535 this.clazz = checkNotNull(clazz); 536 } 537 538 @Override 539 public boolean apply(Class<?> input) { 540 return clazz.isAssignableFrom(input); 541 } 542 543 @Override 544 public int hashCode() { 545 return clazz.hashCode(); 546 } 547 548 @Override 549 public boolean equals(@Nullable Object obj) { 550 if (obj instanceof SubtypeOfPredicate) { 551 SubtypeOfPredicate that = (SubtypeOfPredicate) obj; 552 return clazz == that.clazz; 553 } 554 return false; 555 } 556 557 @Override 558 public String toString() { 559 return "Predicates.subtypeOf(" + clazz.getName() + ")"; 560 } 561 562 private static final long serialVersionUID = 0; 563 } 564 565 /** @see Predicates#in(Collection) */ 566 private static class InPredicate<T extends @Nullable Object> 567 implements Predicate<T>, Serializable { 568 private final Collection<?> target; 569 570 private InPredicate(Collection<?> target) { 571 this.target = checkNotNull(target); 572 } 573 574 @Override 575 public boolean apply(@ParametricNullness T t) { 576 try { 577 return target.contains(t); 578 } catch (NullPointerException | ClassCastException e) { 579 return false; 580 } 581 } 582 583 @Override 584 public boolean equals(@Nullable Object obj) { 585 if (obj instanceof InPredicate) { 586 InPredicate<?> that = (InPredicate<?>) obj; 587 return target.equals(that.target); 588 } 589 return false; 590 } 591 592 @Override 593 public int hashCode() { 594 return target.hashCode(); 595 } 596 597 @Override 598 public String toString() { 599 return "Predicates.in(" + target + ")"; 600 } 601 602 private static final long serialVersionUID = 0; 603 } 604 605 /** @see Predicates#compose(Predicate, Function) */ 606 private static class CompositionPredicate<A extends @Nullable Object, B extends @Nullable Object> 607 implements Predicate<A>, Serializable { 608 final Predicate<B> p; 609 final Function<A, ? extends B> f; 610 611 private CompositionPredicate(Predicate<B> p, Function<A, ? extends B> f) { 612 this.p = checkNotNull(p); 613 this.f = checkNotNull(f); 614 } 615 616 @Override 617 public boolean apply(@ParametricNullness A a) { 618 return p.apply(f.apply(a)); 619 } 620 621 @Override 622 public boolean equals(@Nullable Object obj) { 623 if (obj instanceof CompositionPredicate) { 624 CompositionPredicate<?, ?> that = (CompositionPredicate<?, ?>) obj; 625 return f.equals(that.f) && p.equals(that.p); 626 } 627 return false; 628 } 629 630 @Override 631 public int hashCode() { 632 return f.hashCode() ^ p.hashCode(); 633 } 634 635 @Override 636 public String toString() { 637 // TODO(cpovirk): maybe make this look like the method call does ("Predicates.compose(...)") 638 return p + "(" + f + ")"; 639 } 640 641 private static final long serialVersionUID = 0; 642 } 643 644 /** 645 * @see Predicates#contains(Pattern) 646 */ 647 @GwtIncompatible // Only used by other GWT-incompatible code. 648 private static class ContainsPatternPredicate implements Predicate<CharSequence>, Serializable { 649 final CommonPattern pattern; 650 651 ContainsPatternPredicate(CommonPattern pattern) { 652 this.pattern = checkNotNull(pattern); 653 } 654 655 @Override 656 public boolean apply(CharSequence t) { 657 return pattern.matcher(t).find(); 658 } 659 660 @Override 661 public int hashCode() { 662 // Pattern uses Object.hashCode, so we have to reach 663 // inside to build a hashCode consistent with equals. 664 665 return Objects.hashCode(pattern.pattern(), pattern.flags()); 666 } 667 668 @Override 669 public boolean equals(@Nullable Object obj) { 670 if (obj instanceof ContainsPatternPredicate) { 671 ContainsPatternPredicate that = (ContainsPatternPredicate) obj; 672 673 // Pattern uses Object (identity) equality, so we have to reach 674 // inside to compare individual fields. 675 return Objects.equal(pattern.pattern(), that.pattern.pattern()) 676 && pattern.flags() == that.pattern.flags(); 677 } 678 return false; 679 } 680 681 @Override 682 public String toString() { 683 String patternString = 684 MoreObjects.toStringHelper(pattern) 685 .add("pattern", pattern.pattern()) 686 .add("pattern.flags", pattern.flags()) 687 .toString(); 688 return "Predicates.contains(" + patternString + ")"; 689 } 690 691 private static final long serialVersionUID = 0; 692 } 693 694 /** 695 * @see Predicates#containsPattern(String) 696 */ 697 @GwtIncompatible // Only used by other GWT-incompatible code. 698 private static class ContainsPatternFromStringPredicate extends ContainsPatternPredicate { 699 700 ContainsPatternFromStringPredicate(String string) { 701 super(Platform.compilePattern(string)); 702 } 703 704 @Override 705 public String toString() { 706 return "Predicates.containsPattern(" + pattern.pattern() + ")"; 707 } 708 709 private static final long serialVersionUID = 0; 710 } 711 712 private static <T extends @Nullable Object> List<Predicate<? super T>> asList( 713 Predicate<? super T> first, Predicate<? super T> second) { 714 // TODO(kevinb): understand why we still get a warning despite @SafeVarargs! 715 return Arrays.<Predicate<? super T>>asList(first, second); 716 } 717 718 private static <T> List<T> defensiveCopy(T... array) { 719 return defensiveCopy(Arrays.asList(array)); 720 } 721 722 static <T> List<T> defensiveCopy(Iterable<T> iterable) { 723 ArrayList<T> list = new ArrayList<>(); 724 for (T element : iterable) { 725 list.add(checkNotNull(element)); 726 } 727 return list; 728 } 729}