Function Interface in Java with Examples

08 Dec, 2021
The Function Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in one argument and produces a result. Hence this functional interface takes in 2 generics namely as follows:
T: denotes the type of the input argument
R: denotes the return type of the function
The lambda expression assigned to an object of Function type is used to define its apply() which eventually applies the given function on the argument. 
The Function interface consists of the following 4 methods as listed which are later discussed as follows:
apply()andThen()compose()identity()
apply()
andThen()
compose()
identity()
Method 1: apply()
Syntax: 
R apply(T t)
Parameters: This method takes in only one parameter t which is the function argument
Return Type: This method returns the function result which is of type R.
Example 
Java
// Java Program to Illustrate Functional Interface// Via apply() method // Importing interfaceimport java.util.function.Function; // Main classpublic class GFG {     // Main driver method    public static void main(String args[])    {        // Function which takes in a number        // and returns half of it        Function<Integer, Double> half = a -> a / 2.0;         // Applying the function to get the result        System.out.println(half.apply(10));    }}
5.0
Method 2: andThen()
It returns a composed function wherein the parameterized function will be executed after the first one. If evaluation of either function throws an error, it is relayed to the caller of the composed function.
Syntax:  
default <V> Function<T, V> 
andThen(Function<? super R, ? extends V> after)
where V is the type of output of the after function, and of the composed function
Parameters: This method accepts a parameter after which is the function to be applied after the current one.\
Return Value: This method returns a composed function that applies the current function first and then the after function
Exception: This method throws NullPointerException if the after function is null.
Example 1:
Java
// Java Program to illustrate addThen() method // Importing interfaceimport java.util.function.Function; // Main classpublic class GFG {     // main driver method    public static void main(String args[])    {        // Function which takes in a number and        // returns half of it        Function<Integer, Double> half = a -> a / 2.0;         // Now treble the output of half function        half = half.andThen(a -> 3 * a);         // Applying the function to get the result        // and printing on console        System.out.println(half.apply(10));    }}
15.0
Example 2: To demonstrate when NullPointerException is returned. 
Java
// Java Program to illustrate addThen() method// When NullPointerException occurs // Importing interfaceimport java.util.function.Function; // Main classpublic class GFG {     // Main driver method    public static void main(String args[])    {         // Function which takes in a number and        // returns half of it        Function<Integer, Double> half = a -> a / 2.0;         // Try block to check for exce3ptions        try {             // Trying to pass null as parameter            half = half.andThen(null);        }         // Catch block to handle exceptions        catch (Exception e) {             // Print statement            System.out.println("Exception thrown "                               + "while passing null: "                               + e);        }    }}
Exception thrown while passing null: java.lang.NullPointerException
Method 3: compose()
It returns a composed function wherein the parameterized function will be executed first and then the first one. If evaluation of either function throws an error, it is relayed to the caller of the composed function.
Syntax:  
default <V> Function<V, R> 
compose(Function<? super V, ? extends T> before)
Where V is the type of input of the before function, and of the composed function
Parameters: This method accepts a parameter before which is the function to be applied first and then the current one
Return Value: This method returns a composed function that applies the current function after the parameterized function
Exception: This method throws NullPointerException if the before function is null.
Example 1:
Java
// Java Program to illustrate compose() method // Importing Function interfaceimport java.util.function.Function; // Main classpublic class GFG {     // Main driver method    public static void main(String args[])    {        // Function which takes in a number and        // returns half of it        Function<Integer, Double> half = a -> a / 2.0;         // However treble the value given to half function        half = half.compose(a -> 3 * a);         // Applying the function to get the result        System.out.println(half.apply(5));    }}
7.5
Example 2: When NullPointerException is returned. 
Java
// Java Program to illustrate compose() method // Importing Function interfaceimport java.util.function.Function; // Main classpublic class GFG {     // Main driver method    public static void main(String args[])    {        // Function which takes in a number and        // returns half of it        Function<Integer, Double> half = a -> a / 2.0;         // Try bloc kto check for exceptions        try {             // Trying to pass null as parameter            half = half.compose(null);        }         // Catch block to handle exceptions        catch (Exception e) {             // Print statement            System.out.println("Exception thrown "                               + "while passing null: "                               + e);        }    }}
Exception thrown while passing null: java.lang.NullPointerException
Method 4: identity()
This method returns a function that returns its only argument.
Syntax:  
static <T> Function<T, T> identity()
where T denotes the type of the argument and the value to be returned
Returns: This method returns a function that returns its own argument
Example 
Java
// Java Program to Illustrate identity() method // Importing Function interfaceimport java.util.function.Function; // Main classpublic class GFG {     // Main driver method    public static void main(String args[])    {        // Function which takes in a number and        // returns it        Function<Integer, Integer> i = Function.identity();         // Print statement        System.out.println(i.apply(10));    }}
10
hristinag
popliparul20
sumitgumber28
Java - util package
Java 8
java-basics
Java-Functions
java-interfaces
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
Stack Class in Java