Java 8 - BiFunction example

BiFunction in Java 8 is a functional interface that takes two arguments (Type T, U) and returns an object (Type R).

public interface BiFunction<T, U, R> {

    R apply(T t, U u);

}

Example 1 : BiFunction

The following example shows the implementation of BiFunction and how apply() works. Passing two arguments to apply() returns the result.

import java.util.function.BiFunction;

public class BiFunctionExample1 {

    public static void main(String[] args) {

        BiFunction<String, String, String> func1 = (s1, s2) -> {
            String s3 = s1 + s2;
            return s3;
        };
        String result = func1.apply("Hello", "World");
        System.out.println(result);

        BiFunction<Integer, Integer, Double> func2 = (a1, a2) -> Double.valueOf(a1 + a2);
        Double sum = func2.apply(10, 100);
        System.out.println(sum);
    }
}

Output:

HelloWorld
110.0

Example 2 : andThen()

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

import java.util.function.BiFunction;
import java.util.function.Function;

public class BiFunctionExample2 {

    public static void main(String[] args) {

        BiFunction<Integer, Integer, Double> func1 = (a1, a2) -> Math.pow(a1, a2);
        Function<Double, String> func2 = (a1) -> "Result: " + a1;

        String result = func1.andThen(func2).apply(2, 3);

        System.out.println(result);
    }
}

Output:

Result: 8.0

Example 3

This example defines a function called powAndReturnString(), fixes func1 above, and creates various functions by passing func2 as an argument. Depending on the Lambda object passed to powAndReturnString(), different results may be returned.

import java.util.function.BiFunction;
import java.util.function.Function;

public class BiFunctionExample3 {

    public static void main(String[] args) {

        String result = powAndReturnString(2, 3, (num)-> "result: " + num);
        System.out.println(result);

        result = powAndReturnString(2, 3, (num)-> "PowPow: " + num);
        System.out.println(result);

    }

    public static String powAndReturnString(Integer num1, Integer num2,
                                            Function<Double, String> funcConvert) {
        BiFunction<Integer, Integer, Double> funcPow = (a1, a2) -> Math.pow(a1, a2);
        return funcPow.andThen(funcConvert).apply(num1, num2);
    }
}

Output:

result: 8.0
PowPow: 8.0

Reference

codechachaCopyright ©2019 codechacha