Java 8 Predicate with Examples
[toc]
A Functional Interface is an Interface which allows only one Abstract method within the Interface scope. There are some predefined functional interface in Java like Predicate, consumer, supplier etc. The return type of a Lambda function (introduced in JDK 1.8) is a also functional interface.The Functional Interface PREDICATE is defined in the java.util.function package. It improves manageability of code, helps in unit-testing them separately, and contain some methods like:
函数式接口是一种接口,在一个接口内只允许一个抽象方法。Java中有许多预定义的函数式接口,如:断言predicate,消费者consumer, 提供者supplier,等等。从jdk1.8引入,lambada函数的返回类型,也是一个函数式接口。函数式接口PREDICATE在 java.util.function 包中定义。它增加了代码的可维护性,有助于分离代码进行单元测试,并且包含了一些方法,如:
1. isEqual(Object targetRef)
: Returns a predicate that tests if two arguments are equal according to Objects.equals(Object, Object).
static Predicate isEqual(Object targetRef)
Returns a predicate that tests if two arguments are equal according to Objects.equals(Object, Object).
T : the type of arguments to the predicate Parameters:
targetRef : the object reference with which to compare for equality, which may be null
Returns: a predicate that tests if two arguments are equal according to Objects.equals(Object, Object)
2. and(Predicate other)
: Returns a composed predicate that represents a short-circuiting logical AND of this predicate and another.
default Predicate and(Predicate other)
Returns a composed predicate that represents a
short-circuiting logical AND of this predicate and another.
Parameters:
other: a predicate that will be logically-ANDed with this predicate
Returns : a composed predicate that represents the short-circuiting
logical AND of this predicate and the other predicate
Throws: NullPointerException - if other is null
3. negate()
: Returns a predicate that represents the logical negation of this predicate
default Predicate negate()
Returns:a predicate that represents the logical negation of this predicate
4.or(Predicate other)
: Returns a composed predicate that represents a short-circuiting logical OR of this predicate and another.
default Predicate or(Predicate other)
Parameters:
other : a predicate that will be logically-ORed with this predicate
Returns:a composed predicate that represents the short-circuiting logical OR of this predicate and the other predicate
Throws : NullPointerException - if other is null
5.test(T t)
: Evaluates this predicate on the given argument.boolean test(T t)
test(T t)
Parameters: t - the input argument
Returns: true if the input argument matches the predicate, otherwise false
illustrate
Simple Predicate
// Java program to illustrate Simple Predicate
import java.util.function.Predicate;
public class PredicateInterfaceExample1 {
public static void main(String[] args)
{
// Creating predicate
Predicate<Integer> lesserthan = i -> (i < 18);
// Calling Predicate method
System.out.println(lesserthan.test(10));
//True
}
}
Predicate Chaining
// Java program to illustrate Predicate Chaining
import java.util.function.Predicate;
public class PredicateInterfaceExample2 {
public static void main(String[] args)
{
Predicate<Integer> greaterThanTen = (i) -> i > 10;
// Creating predicate
Predicate<Integer> lowerThanTwenty = (i) -> i < 20;
boolean result = greaterThanTen.and(lowerThanTwenty).test(15);
System.out.println(result);
// Calling Predicate method
boolean result2 = greaterThanTen.and(lowerThanTwenty).negate().test(15);
System.out.println(result2);
//output
//True
//False
}
}
passing Predicate into function
// Java program to illustrate passing Predicate into function
import java.util.function.Predicate;
class PredicateInterfaceExample3 {
static void pred(int number, Predicate<Integer> predicate)
{
if (predicate.test(number)) {
System.out.println("Number " + number);
}
}
public static void main(String[] args)
{
pred(10, (i) -> i > 7);
//output
//Number 10
}
}
OR Predicate
// Java program to illustrate OR Predicate
import java.util.function.Predicate;
class PredicateInterfaceExample4 {
public static Predicate<String> hasLengthOf10 = new Predicate<String>() {
@Override
public boolean test(String t)
{
return t.length() > 10;
}
};
public static void predicate_or()
{
Predicate<String> containsLetterA = p -> p.contains("A");
String containsA = "And";
boolean outcome = hasLengthOf10.or(containsLetterA).test(containsA);
System.out.println(outcome);
}
public static void main(String[] args)
{
predicate_or();
}
//output: True
}
AND Predicate
// Java program to illustrate AND Predicate
import java.util.function.Predicate;
import java.util.Objects;
class PredicateInterfaceExample5 {
public static Predicate<String> hasLengthOf10 = new Predicate<String>() {
@Override
public boolean test(String t)
{
return t.length() > 10;
}
};
public static void predicate_and()
{
Predicate<String> nonNullPredicate = Objects::nonNull;
String nullString = null;
boolean outcome = nonNullPredicate.and(hasLengthOf10).test(nullString);
System.out.println(outcome);
String lengthGTThan10 = "Welcome to the machine";
boolean outcome2 = nonNullPredicate.and(hasLengthOf10).
test(lengthGTThan10);
System.out.println(outcome2);
}
public static void main(String[] args)
{
predicate_and();
}
//output
//False
//True
}
接口源码
@FunctionalInterface
public interface Predicate<T> {
/**
* 具体过滤操作 需要被子类实现.
* 用来处理参数T是否满足要求,可以理解为 条件A
*/
boolean test(T t);
/**
* 调用当前Predicate的test方法之后再去调用other的test方法,相当于进行两次判断
* 可理解为 条件A && 条件B
*/
default Predicate<T> and(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) && other.test(t);
}
/**
* 对当前判断进行"!"操作,即取非操作,可理解为 ! 条件A
*/
default Predicate<T> negate() {
return (t) -> !test(t);
}
/**
* 对当前判断进行"||"操作,即取或操作,可以理解为 条件A ||条件B
*/
default Predicate<T> or(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) || other.test(t);
}
/**
* 对当前操作进行"="操作,即取等操作,可以理解为 A == B
*/
static <T> Predicate<T> isEqual(Object targetRef) {
return (null == targetRef)
? Objects::isNull
: object -> targetRef.equals(object);
}
}