Part-4 Functional Interface(Function)

Published: (March 3, 2026 at 04:09 AM EST)
2 min read
Source: Dev.to

Source: Dev.to

Functional Interface: Function

A functional interface in java.util.function that represents a transformation: it takes an input of type T and produces an output of type R.

Core Method

R apply(T t);

Extra Methods

andThen(Function after)

Chains another function to be executed after the current one.

Function lengthFinder = str -> str.length();
Function square = n -> n * n;

Function lengthSquared = lengthFinder.andThen(square);

System.out.println(lengthSquared.apply("Java")); // 16

compose(Function before)

Applies another function before the current one.

Function square = n -> n * n;
Function toString = n -> "Result: " + n;

Function squareThenString = toString.compose(square);

System.out.println(squareThenString.apply(5)); // Result: 25

Example: Function Order Demo

import java.util.function.Function;

public class FunctionOrderDemo {
    public static void main(String[] args) {

        Function add2 = n -> n + 2;
        Function multiply3 = n -> n * 3;

        // andThen → current first, then after
        System.out.println(add2.andThen(multiply3).apply(5));
        // (5 + 2) * 3 = 21

        // compose → before first, then current
        System.out.println(add2.compose(multiply3).apply(5));
        // (5 * 3) + 2 = 17
    }
}

When to Use andThen vs. compose

  • andThen is sufficient when you want to apply the current function first and then another function (current → after).
  • compose is useful when you need to preprocess the input before applying the main function (before → current).
0 views
Back to Blog

Related posts

Read more »

Part-3 Functional Interface (Consumer)

Consumer Consumer is a functional interface in java.util.function. It represents an operation that takes one input and returns nothing. Core method java void a...