2.6.  Develop code that uses the Predicate interface

[Note]

The java.util.function.Predicate<T> interface defines an abstract method named test(T t) that accepts an object of generic type T and returns a boolean primitive.


package java.util.function;

@FunctionalInterface
public interface Predicate<T extends Object> {

    public boolean test(T t);

    ...

}

					

You might want to use this interface when you need to represent a boolean expression that uses an object of type T. For example, you can define a lambda that accepts String objects, as shown in the following listing:


Predicate<String> longString = s -> s.length() > 5;

// Will print true
System.out.print(longString.test("Hi there !"));

					

Predicates may also be passed into functions:


Predicate<String> longString = s -> s.length() > 5;
validateString("Hello again !", longString);
...
...
void validateString(String s, Predicate<String> p) {
    if (p.test(s)) {
        System.out.print("Test passed !");
    }
}

					

Professional hosting         Free 'Oracle Certified Expert Web Services Developer 6' Guide     Exam 1Z0-810: Upgrade to Java SE 8 Programmer Quiz