Java 8 - Function example

Function in Java 8 is a functional interface that takes one argument (Type T) and returns one object (Type R).

public interface Function<T, R> {

    R apply(T t);

}

Example 1 : Function

The following example shows the Function implementation and how apply() works. Passing an Integer object to apply() returns the result as an Integer object.

import java.util.function.Function;

public class FunctionExample1 {

    public static void main(String[] args) {

        Function<Integer, Integer> func1 = x -> x * x;

        Integer result = func1.apply(10);

        System.out.println(result);
    }
}

Output:

100

Example 2 : andThen()

The following example shows how andThen() works. The argument of apply() is first passed to func1, and the result of func1 is passed as an argument to func2. And the result of func2 is returned.

import java.util.function.Function;

public class FunctionExample2 {

    public static void main(String[] args) {

        Function<Integer, Integer> func1 = n -> n * n;
        Function<Integer, String> func2 = n -> "result: " + n;

        String result = func1.andThen(func2).apply(10);

        System.out.println(result);
    }
}

Output:

result: 100

Example 3 : compose()

The following example introduces compose(). multiply.compose(add) composes the add and multiply functions. addAndMultiply.apply(1) is passed 1 as an argument to the add function, the result is passed to the multiply function, and the result is returned.

import java.util.function.Function;

public class FunctionExample3 {

    public static void main(String[] args) {

        Function<Integer, Double> add = n -> n + 2.0;
        Function<Double, Double> multiply = n -> n * 5.0;
        Function<Integer, Double> addAndMultiply = multiply.compose(add);

        Double result = addAndMultiply.apply(1);

        System.out.println(result);
    }
}

Output:

15.0

Reference

codechachaCopyright ©2019 codechacha