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