What is the Function functional interface in Java?

Function is a functional interface that accepts one argument and returns a result. The apply() method of the interface is the functional method.

The Function interface is defined in the java.util.function package. To import the Function interface, check the following import statement:

import java.util.function.Function;

Syntax


R apply(T t);

Parameters

  • T t: This is the function argument.

Return value

The method returns the function result.

Code

import java.util.function.Function;
public class Main {
public static void main(String[] args){
Function<Integer, Integer> addFunction = arg -> arg + 5;
int arg = 1;
System.out.println("Result of apply() on addFunction --> " + addFunction.apply(arg));
}
}

Explanation

  • Line 1: We import the Function interface from the function package.
  • Line 6: We define an implementation of the Function interface called addFunction. addFunction accepts an integer and returns the result of adding 5 to the given integer.
  • Line 7: We define an integer called arg.
  • Line 8: We print the result of using the apply() method and pass arg as an argument.

Free Resources