BiFunction
is a functional interface, which accepts two arguments and returns a result. The interface contains two methods:
apply()
methodandThen()
methodThe BiFunction
interface is defined in the java.util.function
package. To import the BiFunction
interface, we use the following statement:
import java.util.function.BiFunction;
The apply()
method applies the function to the given arguments and returns the result of that function. This is the functional method of the interface.
R apply(T t, U u)
T t
: This is the first argument.U u
: This is the second argument.This method returns the result of the function.
In the code written below, we create a BiFunction
interface that accepts two string arguments and returns the result of the concatenation of the two strings:
import java.util.function.BiFunction;public class Main{public static void main(String[] args) {// This implementation concats the argument strings passed as parametersBiFunction<String, String, String> concatStrings = (s, s2) -> s.concat(s2);String s1 = "hello";String s2 = "-educative";// calling apply method of the BiFunctionSystem.out.println(concatStrings.apply(s1, s2));}}
The andThen()
method is used to chain together multiple Function
functional interface implementations, such that the result of the first implementation becomes the input to the second implementation. This method returns a composed function of different functions defined in the order. If the evaluation of either function throws an exception, it is relayed to the caller of the composed function.
default <V> BiFunction<T, U, V> andThen(Function<? super R, ? extends V> after)
Function<? super R, ? extends V> after
: This is the function that needs to be applied after the current function is applied.This method returns a composed function.
import java.util.function.BiFunction;import java.util.function.Function;public class Main{public static void main(String[] args) {BiFunction<String, String, String> concatStrings = (s1, s2) -> s1.concat(s2);Function<String, String> concatConstants = (s1) -> s1.concat("/edpresso");Function<String, String> convertToUpperCase = String::toUpperCase;String s1 = "Hello";String s2 = " educative";BiFunction<String, String, String> stage1 = concatStrings.andThen(concatConstants);BiFunction<String, String, String> stage2 = stage1.andThen(convertToUpperCase);// calling andThen method of the BiFunctionSystem.out.println(stage2.apply(s1, s2));}}
In the code written above, we define a BiFunction
(concatStrings
) and two different Function
(concatConstants
and convertToUpperCase
) implementations.
The composition of the functions is divided into two stages:
concatStrings
and concatConstants
. The result of this is stored in stage1
.stage1
and convertToUpperCase
. The result of this is stored in stage2
.apply
method on the stage2
composed object.