InterviewSolution
| 1. |
Predicate in Java 8 |
|
Answer» Predicate is a FUNCTIONAL interface defined in java.util.Function package. It helps in improving the control of the code. It can be used as an assignment target in lambda expressions and functional interfaces. Functional interfaces are those interfaces that have only ONE abstract method. Here is the declaration @FunctionalInterface public interface Predicate <T>Methods: boolean test(T t)The test() method evaluates the predicate BASED on the given argument. default Predicate<T> and(Predicate<? super T> other)The and() method returns a formulated predicate by short circuited logical AND of this predicate and the other. If the other is null, it throws a NullPointerException. If this predicate is false, the other is not evaluated. default Predicate<T> negate()The negate() method returns a predicate that REPRESENTS the logical NOT of this predicate. default Predicate<T> or(Predicate<? super T> other)The or() method returns a formulated predicated by short circuited OR of this predicate and the other. If this predicate is true, the other is not evaluated. static <T> Predicate<T> isEqual(Object targetRef)The isEqual() method returns a predicate that tests if two arguments are equal according to Objects.equals(Object, Object). Here is a SAMPLE program for Predicates in Java : import java.util.function.Predicate; public class Example { public static void main(String[] args) { Predicate<Integer> a = n-> (n%3==0); // Creating predicate with lambda expression System.out.println(a.test(36)); // Calling Predicate method test(Object) } }The output is as follows: $javac Example.java $java Example true |
|