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 X

Look at java.util.function.Function Javadoc description below:

Function_Signature_Java8_Techndeck

Function Interface contains 4 methods:

  1. apply

  2. compose

  3. andThen

  4. 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:

Other Useful References:

Author

  • Deepak Verma

    Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester.

    He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.

    View all posts