java.util.function.Function is a functional interface as part of java.util.function package which is introduced in Java 8. It is an in-built Functional Interface. This function expects one argument and produces a result. In this post, we are going to see several implementations of Function Interface using different examples.
java.util.function.Function Interface in Java 8 with Examples...!!! Share on XLook at java.util.function.Function Javadoc description below:

Function Interface contains 4 methods:
-
apply
-
compose
-
andThen
-
identity
Lets understand above mentioned methods thorough various examples:
Example 1. ‘apply’ method
Below example shows how to use ‘apply’ method of ‘Function’ interface using Lambda expression.
import java.util.function.Function;
public class FunctionInterfaceJava8Example_with_apply {
public static void main(String[] args) {
System.out.println("Function Interface - 'apply' example \n");
Function <Integer, Integer> functionObj = i -> i * 2;
System.out.println("Double of 5 : " + functionObj.apply(5));
}
}
Output:
Function Interface - 'apply' example Double of 5 : 10
Example 2. ‘andThen’ & ‘compose’ methods
Below example shows how to use ‘andThen’ & ‘compose’ methods of ‘Function’ interface using Lambda expression.
import java.util.function.Function;
public class FunctionInterfaceJava8Example_with_andThen_Compose {
public static void main(String[] args) {
System.out.println("Function Interface - 'andThen' & 'compose' example \n");
Function <Integer, Integer> functionObj1 = i -> i * 10;
Function <Integer, Integer> functionObj2 = i -> i / 2;
//andThen operation
System.out.println("Result of 'andThen' method: " + functionObj1.andThen(functionObj2).apply(4));
//compose operation
System.out.println("Result of 'compose' method: " + functionObj1.compose(functionObj2).apply(4));
}
}
Output:
Function Interface - 'andThen' & 'compose' example Result of 'andThen' method: 20 Result of 'compose' method: 20
Do you like this Post? – then check my other helpful posts:
- Passing Function as a Parameter in another Method in Java 8
- Collection sorting using Lambda in Java 8
- Supplier Interface in Java 8 with Examples