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