Functional interfaces have one functionality to exhibit. For instance, a Comparable interface with one method ‘compareTo’ is employed for comparison purposes. Java 8 has defined tons of functional interfaces to be used extensively in lambda expressions. Following is the list of functional interfaces defined in java.util.Function package.
Below is the directory of Interfaces in Java8.
Predicate <T> interface may be a functional interface with a way test(Object) to return a Boolean value. Although, this associate signifies that an object is tested to be true or false.
Create the subsequent Java program using any editor of your choice in, say, C:\> JAVA.
Java8Tester.java
import java.util.Arrays; import java.util.List; import java.util.function.Predicate; public class Java8Tester { public static void main(String args[]) { List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9); // Predicate<Integer> predicate = n -> true // n is passed as parameter to test method of Predicate interface // test method will always return true no matter what value n has. System.out.println("Print all numbers:"); //pass n as parameter eval(list, n->true); // Predicate<Integer> predicate1 = n -> n%2 == 0 // n is passed as parameter to test method of Predicate interface // test method will return true if n%2 comes to be zero System.out.println("Print even numbers:"); eval(list, n-> n%2 == 0 ); // Predicate<Integer> predicate2 = n -> n > 3 // n is passed as parameter to test method of Predicate interface // test method will return true if n is greater than 3. System.out.println("Print numbers greater than 3:"); eval(list, n-> n > 3 ); } public static void eval(List<Integer> list, Predicate<Integer> predicate) for(Integer n: list) { if(predicate.test(n)) { System.out.println(n + " "); } } } }
Above we have proceeded the predicate interface, In which a single output is taken and returns Boolean
Assemble the class using javac compiler as follows:
C:\JAVA>javac Java8Tester.java
Now, you have to run the Java8Tester as follows:
C:\JAVA>java Java8Tester
Your Output must look like this:
Print all numbers: 1 2 3 4 5 6 7 8 9 Print even numbers: 2 4 6 8 Print numbers greater than 3: 4 5 6 7 8 9