The Wayback Machine - https://web.archive.org/web/20241001012414/https://www.geeksforgeeks.org/function-interface-in-java-with-examples/
Open In App

Function Interface in Java with Examples

Last Updated : 07 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.
 

Methods in Function Interface

The Function interface consists of the following 4 methods as listed which are later discussed as follows:

  1. apply()
  2. andThen()
  3. compose()
  4. 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 interface
import java.util.function.Function;

// Main class
public 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));
    }
}

Output
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 interface
import java.util.function.Function;

// Main class
public 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 triple 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));
    }
}

Output
15.0

Example 2: To demonstrate when NullPointerException is returned.
 

Java
// Java Program to illustrate addThen() method
// When NullPointerException occurs

// Importing interface
import java.util.function.Function;

// Main class
public 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 exceptions
        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);
        }
    }
}

Output
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 interface
import java.util.function.Function;

// Main class
public 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;

        // Triple 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));
    }
}

Output
7.5

Example 2: When NullPointerException is returned.
 

Java
// Java Program to illustrate compose() method

// Importing Function interface
import java.util.function.Function;

// Main class
public 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 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);
        }
    }
}

Output
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 interface
import java.util.function.Function;

// Main class
public 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));
    }
}

Output
10


Previous Article
Next Article

Similar Reads

Why to Use Comparator Interface Rather than Comparable Interface in Java?
In Java, the Comparable and Comparator interfaces are used to sort collections of objects based on certain criteria. The Comparable interface is used to define the natural ordering of an object, whereas the Comparator interface is used to define custom ordering criteria for an object. Here are some reasons why you might want to use the Comparator i
8 min read
Java.util.function.BiPredicate interface in Java with Examples
The BiPredicate<T, V> interface was introduced in JDK 8. This interface is packaged in java.util.function package. It operates on two objects and returns a predicate value based on that condition. It is a functional interface and thus can be used in lambda expression also. public interface BiPredicate<T, V> Methods: test(): This functio
2 min read
Java.util.function.DoublePredicate interface in Java with Examples
The DoublePredicate interface was introduced in JDK 8. This interface is packaged in java.util.function package. It operates on a Double object and returns a predicate value based on a condition. It is a functional interface and thus can be used in lambda expression also. public interface DoublePredicate Methods test(): This function evaluates a co
2 min read
Java.util.function.LongPredicate interface in Java with Examples
The LongPredicate interface was introduced in JDK 8. This interface is packaged in java.util.function package. It operates on a long value and returns a predicate value based on a condition. It is a functional interface and thus can be used in lambda expression also. public interface LongPredicate Methods test(): This function evaluates a condition
2 min read
Java.util.function.IntPredicate interface in Java with Examples
The IntPredicate interface was introduced in JDK 8. This interface is packaged in java.util.function package. It operates on an integer value and returns a predicate value based on a condition. It is a functional interface and thus can be used in lambda expression also. public interface IntPredicate Methods: test(): This function evaluates a condit
2 min read
Java.util.function.DoubleBinaryOperator interface with Examples
The DoubleBinaryOperator interface was introduced in Java 8. It represents an operation on two double values and returns the result as a double value. It is a functional interface and thus can be used as a lambda expression or in a method reference. It is mostly used when the operation needs to be encapsulated from the user. Methods: applyAsDouble(
2 min read
Java.util.function.LongBinaryOperator interface with Examples
The LongBinaryOperator interface was introduced in Java 8. It represents an operation on two long values and returns the result as a long value. It is a functional interface and thus can be used as a lambda expression or in a method reference. It is mostly used when the operation needs to be encapsulated from the user. Methods: applyAsLong(): This
1 min read
Java.util.function.IntBinaryOperator interface with Examples
The IntBinaryOperator interface was introduced in Java 8. It represents an operation on two int values and returns the result as an int value. It is a functional interface and thus can be used as a lambda expression or in a method reference. It is mostly used when the operation needs to be encapsulated from the user. Methods applyAsInt(): This func
2 min read
Java 8 | IntToDoubleFunction Interface in Java with Examples
The IntToDoubleFunction 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 an int-valued argument and gives a double-valued result. The lambda expression assigned to an object of IntToDoubleFunction type is used to define
1 min read
Java 8 | DoubleToLongFunction Interface in Java with Examples
The DoubleToLongFunction 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 a double-valued argument and gives an long-valued result. The lambda expression assigned to an object of DoubleToLongFunction type is used to defi
1 min read
ToLongFunction Interface in Java with Examples
The ToLongFunction 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 an argument of type T and produces a long-valued result. This functional interface takes in only one generic, namely:- T: denotes the type of the input
1 min read
LongToIntFunction Interface in Java with Examples
The LongToIntFunction 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 a long-valued argument and gives an int-valued result. The lambda expression assigned to an object of DoubleToLongFunction type is used to define its
1 min read
ToIntFunction Interface in Java with Examples
The ToIntFunction 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 an argument of type T and produces an int-valued result. This functional interface takes in only one generic, namely:- T: denotes the type of the input a
1 min read
ToDoubleFunction Interface in Java with Examples
The ToDoubleFunction 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 an argument of type T and produces a double-valued result. This functional interface takes in only one generic, namely:- T: denotes the type of the in
1 min read
IntFunction Interface in Java with Examples
The IntFunction 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 an int-valued argument and produces a result of type R. This functional interface takes in only one generic, namely:- R: denotes the type of the output of
1 min read
LongFunction Interface in Java with Examples
The LongFunction 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 a long-valued argument and produces a result of type R. This functional interface takes in only one generic, namely:- R: denotes the type of the output of
1 min read
Supplier Interface in Java with Examples
The Supplier 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 does not take in any argument but produces a value of type T. Hence this functional interface takes in only one generic namely:- T: denotes the type of the result The
1 min read
IntConsumer Interface in Java with Examples
The IntConsumer 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 int-valued argument but does not return any value. The lambda expression assigned to an object of IntConsumer type is used to define its accept() which
3 min read
LongConsumer Interface in Java with Examples
The LongConsumer 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 long-valued argument but does not return any value. The lambda expression assigned to an object of LongConsumer type is used to define its accept() wh
3 min read
Java 8 | LongSupplier Interface with Examples
The LongSupplier 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 does not take in any argument but produces a long value. The lambda expression assigned to an object of LongSupplier type is used to define its getAsLong() which e
1 min read
Java 8 | IntSupplier Interface with Examples
The IntSupplier 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 does not take any argument but produces an int value. The lambda expression assigned to an object of IntSupplier type is used to define its getAsInt() which eventua
1 min read
Java 8 | BooleanSupplier Interface with Examples
The BooleanSupplier 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 does not take in any argument but produces a boolean value. The lambda expression assigned to an object of BooleanSupplier type is used to define its getAsBoole
1 min read
Java 8 | DoubleSupplier Interface with Examples
The DoubleSupplier 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 does not take in any argument but produces a double value. The lambda expression assigned to an object of DoubleSupplier type is used to define its getAsDouble()
1 min read
Java.util.concurrent.Executor interface with Examples
The concurrent API in Java provides a feature known as an executor that initiates and controls the execution of threads. As such, an executor offers an alternative to managing threads using the thread class. At the core of an executor is the Executor interface. It refers to the objects that execute submitted Runnable tasks. Class hierarchy: java.ut
1 min read
Java.util.concurrent.ExecutorService Interface with Examples
The ExecutorService interface extends Executor by adding methods that help manage and control the execution of threads. It is defined in java.util.concurrent package. It defines methods that execute the threads that return results, a set of threads that determine the shutdown status. The ExecutorService interface is implemented in a utility class c
3 min read
ThreadFactory Interface in Java with Examples
The ThreadFactory interface defined in the java.util.concurrent package is based on the factory design pattern. As its name suggests, it is used to create new threads on demand. Threads can be created in two ways: 1. Creating a class that extends the Thread class and then creating its objects. Java Code import java.io.*; class GFG { public static v
7 min read
Collection Interface in Java with Examples
The Collection interface is a member of the Java Collections Framework. It is a part of java.util package. It is one of the root interfaces of the Collection Hierarchy. The Collection interface is not directly implemented by any class. However, it is implemented indirectly via its subtypes or subinterfaces like List, Queue, and Set. For Example, th
8 min read
Comparable Interface in Java with Examples
The Comparable interface is used to compare an object of the same class with an instance of that class, it provides ordering of data for objects of the user-defined class. The class has to implement the java.lang.Comparable interface to compare its instance, it provides the compareTo method that takes a parameter of the object of that class. In thi
4 min read
Comparator Interface in Java with Examples
A comparator interface is used to order the objects of user-defined classes. A comparator object is capable of comparing two objects of the same class. Following function compare obj1 with obj2. Syntax: public int compare(Object obj1, Object obj2):Suppose we have an Array/ArrayList of our own class type, containing fields like roll no, name, addres
6 min read
SortedMap Interface in Java with Examples
SortedMap is an interface in the collection framework. This interface extends the Map interface and provides a total ordering of its elements (elements can be traversed in sorted order of keys). The class that implements this interface is TreeMap. The SortedMap interface is a subinterface of the java.util.Map interface in Java. It extends the Map i
11 min read