Java Function compose()

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

1. Function compose() Method Overview

Definition:

The Function compose() method allows for the composition of functions, i.e., it returns a composed function that first applies the provided function to its input, and then applies the current function to the result.

Syntax:

default <V> Function<V, R> compose(Function<? super V, ? extends T> before)

Parameters:

- before: The function to apply before the current function.

Key Points:

- The composed function's input type is a type of the before function's input, and its output type is a type of the current function's output.

- If the evaluation of either function throws an exception, it is relayed to the caller of the composed function.

- It's useful for creating a sequence of transformations on data.

2. Function compose() Method Example

import java.util.function.Function;

public class FunctionComposeExample {
    public static void main(String[] args) {
        // Define a Function to double an integer
        Function<Integer, Integer> doubleNumber = num -> num * 2;

        // Define a Function to increment an integer by 1
        Function<Integer, Integer> incrementByOne = num -> num + 1;

        // Compose the functions: double the number and then increment
        Function<Integer, Integer> doubleThenIncrement = doubleNumber.compose(incrementByOne);

        // Apply the composed function
        int result = doubleThenIncrement.apply(5);

        System.out.println("Result after applying composed function: " + result);
    }
}

Output:

Result after applying composed function: 12

Explanation:

In the example provided, we first define two Functions: one to double an integer and another to increment an integer by 1. We then compose these functions using the compose() method. 

The order matters: the increment function is applied first, and then the result is doubled. Thus, for an input of 5, the function first increments it to 6 and then doubles it to 12.

Comments