Function interface in Java 8

Tags: java.util.function.Function Java 8

The java.util.function.Function interface is a functional interface which represents a function that take one argument and return one output result. In this Java 8 tutorial we learn how to use the Function interface in Java program via different use cases.

How to use java.util.function.Function interface in Java 8

In the following Java 8 example program, we use Function functional interface to declare function which can double or triple the input value. FunctionExample1 .java

import java.util.function.Function;

public class FunctionExample1 {
    public static void main(String... args) {
        Function<Integer, Integer> doubleFunc = x -> x * 2;
        Function<Integer, Integer> tripleFunc = x -> x * 3;

        Integer value = 5;
        Integer doubleValue = doubleFunc.apply(value);
        Integer tripleValue = tripleFunc.apply(value);

        System.out.println("Double of " + value + " is " + doubleValue);
        System.out.println("Triple of " + value + " is " + tripleValue);
The output is:
Double of 5 is 10
Triple of 5 is 15

How to chain multiple Function using andThen() method

In the following Java program, we show you how to chain multiple Function using andThen() method.

In this example we have two Function, the first once to get length of a given string, and the second once to double the value of argument. We will chain two Function to get the length of a String and then double that length value to get final result.

import java.util.function.Function;

public class FunctionExample2 {
    public static void main(String... args) {
        // to count number of characters
        Function<String, Integer> countFunc = x -> x.length();
        // to double the value of input
        Function<Integer, Integer> doubleFunction = x -> x * 2;

        Integer result = countFunc.andThen(doubleFunction).apply("simple solution");

        System.out.println("The double of length of input string is: " + result);
The output is:
The double of length of input string is: 30

Happy Coding 😊