Thursday, 10 March 2016

Predicate vs Function in Java 8

Both Predicate and Function are predefined functional interfaces introduced in JDK8. 

These are added in java.util.function package. 

Predicate Interface

This is represented as Predicate<T> where T is an object type input.
The purpose of Predicate<T> is to decide if the object of type T passes some test.
For this,
Predicate interface contains a method test() , which takes one argument and returns a Boolean value.
Here is an example of using Predicate to determine if a number is greater than zero or not.
 import java.util.function.Predicate;
public class PredicateInterfaceDemo {
public static void main(String[] args) {
int num = -10;
Predicate gt_lt = i -&gt; i&gt;0 ;
boolean result = gt_lt.test(num);
System.out.println(num + " greater than zero : "+ result);
 }
}
Running this program will produce :
-10 greater than zero : false
In the above program, a predicate gt_lt was created to test whether a number is greater than zero. Then it was tested with -10 and the test() method of Predicate returned false.

Function Interface

Function interface is represented as Function<T,R> where T is the type of object passed to Function and R is the type of object returned.
Functions are similar to Predicates, but Functions return an object as result while Predicates return Boolean.
For this,
Function interface contains a method called apply() , which takes a one argument and returns an object as result.
Here is an example of Function that takes a string and returns its length.
 import java.util.function.Function;
public class FunctionInterfaceDemo {
public static void main(String[] args) {
Function&lt;String, Integer&gt; length = str -&gt; str.length();
System.out.println("Length of string 'Hello World' is " + length.apply("Hello World"));
}
} 
Running this program will produce following output :
Length of string ‘Hello World’ is 11
In the above example, Function length takes a String as parameter and returns an Integer.
The Function interface has inbuilt apply() function that uses the logic provided to evaluate the length of string “Hello World”.

Difference between Predicate and Function

A Predicate takes one object argument and returns a Boolean value where as a Function takes an object argument and returns an object.
Predicate contains a method test() for testing if the object matches its condition. Function contains apply() method that applies some logic on object parameter and returns an object.

No comments:

Post a Comment