Functional interface in Java 8 stands as a pivotal feature that enables developers to seamlessly blend functional programming with object-oriented programming. Identified by the annotation @FunctionalInterface, it opens up a world of new possibilities. Expanding on this, the java.util.function package offers a range of built-in functional interfaces, further enhancing the capabilities within the Java framework.
The Predicate<T> class features a test method that accepts a parameter of type T. After defining the Predicate function as a lambda expression, you can use this method throughout your code. When you call the test method, it returns a boolean value, indicating the result of the lambda expression defined earlier. This makes Predicate useful for creating condition-based or criteria-based lambda expressions that can be evaluated later with the test method. Refer to the API for additional methods. Below is a simple illustration for your reference.
For example, in the code snippet below I have defined a predicate java function ‘checkGreaterThanTen‘ to evaluate if an input value is greater than 10. The output for an input value of 23 returns ‘true’ as expected (Predicate function defined earlier returns true)

Output

Supplier Function
The Supplier<T> functional interface can be utilized to define a lambda expression or a functional interface that can be reused throughout an application. For instance, if the expression pi * 256 is frequently needed in your program, you can declare it as a supplier and use the get() method to retrieve the expression value whenever required in different parts of the program.
Here is a simple Java Supplier function that multiplies the value of π (pi) by 256. It is named piMultiplier. The output screen demonstrates how to use the Supplier function with the get() method to add 100 to the value returned by the piMultiplier function.
Supplier<Double> piCross256 = () -> Double.valueOf(3.14 * 256);

Leave a Reply