Mownathi Manigundan
2 min readMar 25, 2024

Function Interface in Java 8

The Function Interface is a functional interface which contains single abstract method named apply which takes in an argument of type T and produces a result of type R.

@FunctionalInterface
public interface Function<T,R> {
R apply(T t);
}

It has 2 default methods and a static method

  1. compose method first applies the before function to the input parameter and then applies the function to its result.
default <V> Function<V, R> compose(Function<? super V, ? extends T> before)

2. andThen method first applies the function to its input and then executes the after function to its result

default <V> Function<T, V> andThen(Function<? super R, ? extends V> after)

3. identity method returns the input parameter itself

static <T> Function<T, T> identity()

Example which illustrates the above methods

package com.mowrija;

import java.util.function.Function;

public class FunctionalInterfaceDemo {
public static void main(String[] args) {
Function<Integer, Integer> triple = num -> num * 3;
Function<Integer, Integer> addOne = num -> num + 1;
Function<Integer, Integer> addOneThenTriple = triple.compose(addOne);
Function<Integer, Integer> tripleAndThenAddOne = triple.andThen(addOne);
System.out.println(addOneThenTriple.apply(4)); // (4+1) *3
System.out.println(tripleAndThenAddOne.apply(4)); // (4*3) + 1
System.out.println(Function.identity().apply("Identity function")); //Identity function
}
}

We can employ the Function interface for Memoization to cache the results of expensive function calls and reuse them whenever we find the same input data again.

Below is a sample code to demonstrate how memoization can significantly improve performance by caching results of previous function computations.

package com.mowrija;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;

public class Fibonacci {
private static Map<Integer,Integer> cache = new ConcurrentHashMap<>();

public static void main(String[] args) {
Function<Integer, Integer> fibonacci = Fibonacci::fib;
System.out.println("Fibonacci of 5 is " + fibonacci.apply(5));
System.out.println("Fibonacci of 10 is " + fibonacci.apply(10));
System.out.println("Fibonacci of 15 is " + fibonacci.apply(15));
}

public static int fib (int n) {
if (n <= 1) {
return n;
}
if (cache.containsKey(n)) {
return cache.get(n);
}
int result = fib(n-1) + fib(n-2);
cache.put(n, result);
return result;
}
}