src/share/classes/java/util/function/Predicate.java

Print this page
rev 6273 : 8004561: Additional functional interfaces, extension methods and name changes
Summary: Adds additional functional interfaces for primitives and "Bi" (two operand). Adds utility extension methods. Includes some name changes for existing functional interfaces per EG decisions.
Reviewed-by: briangoetz

@@ -22,10 +22,12 @@
  * or visit www.oracle.com if you need additional information or have any
  * questions.
  */
 package java.util.function;
 
+import java.util.Objects;
+
 /**
  * Determines if the input object matches some criteria.
  *
  * @param <T> the type of input objects to {@code test}
  *

@@ -39,6 +41,56 @@
      * @param t the input object
      * @return {@code true} if the input object matches some criteria, otherwise
      * {@code false}
      */
     public boolean test(T t);
+
+    /**
+     * Returns a predicate which evaluates to {@code true} only if this
+     * predicate and the provided predicate both evaluate to {@code true}. If
+     * this predicate returns {@code false} then the remaining predicate is not
+     * evaluated.
+     *
+     * @return a new predicate which returns {@code true} only if both
+     * predicates return {@code true}.
+     */
+    public default Predicate<T> and(Predicate<? super T> p) {
+        Objects.requireNonNull(p);
+        return (T t) -> test(t) && p.test(t);
+    }
+
+    /**
+     * Returns a predicate which negates the result of this predicate.
+     *
+     * @return a new predicate who's result is always the opposite of this
+     * predicate.
+     */
+    public default Predicate<T> negate() {
+        return (T t) -> !test(t);
+    }
+
+    /**
+     * Returns a predicate which evaluates to {@code true} if either this
+     * predicate or the provided predicate evaluates to {@code true}. If this
+     * predicate returns {@code true} then the remaining predicate is not
+     * evaluated.
+     *
+     * @return a new predicate which returns {@code true} if either predicate
+     * returns {@code true}.
+     */
+    public default Predicate<T> or(Predicate<? super T> p) {
+        Objects.requireNonNull(p);
+        return (T t) -> test(t) || p.test(t);
+    }
+
+    /**
+     * Returns a predicate that evaluates to {@code true} if all or none of the
+     * component predicates evaluate to {@code true}.
+     *
+     * @return  a predicate that evaluates to {@code true} if all or none of the
+     * component predicates evaluate to {@code true}
+     */
+    public default Predicate<T> xor(Predicate<? super T> p) {
+        Objects.requireNonNull(p);
+        return (T t) -> test(t) ^ p.test(t);
+    }
 }