Java Function apply()

In this guide, you will learn about the Function apply() method in Java programming and how to use it with an example.

1. Function apply() Method Overview


The Function.apply() method is a method in the Function interface, used to compute a result using the provided argument and return it. A Function is a part of the java.util.function package, which is a functional interface representing a function that accepts an argument and produces a result.


R apply(T t)


- t: The function argument.

Key Points:

- The Function.apply() method takes one argument and produces a result.

- It is a functional interface and thus can be used as the assignment target for a lambda expression or method reference.

- The primary use case is to transform data from one form to another.

2. Function apply() Method Example

import java.util.function.Function;

public class FunctionApplyExample {
    public static void main(String[] args) {
        // Define a Function to convert an integer to its string representation
        Function<Integer, String> intToString = num -> Integer.toString(num);

        // Define a Function to double an integer
        Function<Integer, Integer> doubleNumber = num -> num * 2;

        // Apply the functions
        String result1 = intToString.apply(5);
        int result2 = doubleNumber.apply(7);

        System.out.println("Result of intToString: " + result1);
        System.out.println("Result of doubleNumber: " + result2);


Result of intToString: 5
Result of doubleNumber: 14


In the example provided, we first define a Function that converts an integer to its string representation. Another Function is defined to double the integer. Using the apply() method, we then compute and print the results. The first function transforms the number 5 into its string form, while the second function doubles the number 7 to produce 14.