BiFunction interface was introduced in Java 8 and is available in java.util.function package. BiFunction represents a function that accepts two arguments and produces a result.
BiFunction is similar to Function interface with the difference that BiFunction accepts two arguments whereas Function arguments accepts one argument.
Methods in BiFunction interface
| default<V> BiFunction<T,U,V> andThen(Function<? super R,? extends V> after) | This method returns a composed function that first applies this function to its input, and then after function is applied to the result. |
| R apply(T t, U u) | Applies this function to the given arguments. |
BiFunction example 1
import java.util.function.BiFunction;
public class BiFunctionExample {
public static void main(String[] args) {
//BiFunction to calculate sum of two numbers
BiFunction<Integer, Integer, Integer> biFunctionSum = (x, y) -> x + y;
//BiFunction to calculate product of two numbers
BiFunction<Integer, Integer, Integer> biFunctionProduct = (x, y) -> x * y;
System.out.println("biFunctionSum result " + biFunctionSum.apply(2, 3));
System.out.println("biFunctionProduct result " + biFunctionProduct.apply(2, 3));
}
}
Output
biFunctionSum result 5
biFunctionProduct result 6
BiFunction andThen() method example
In this example, we’ll first use BiFunction operation to calculate sum to two number and then double the result using andThen() method.
import java.util.function.BiFunction;
import java.util.function.Function;
public class BiFunctionExample {
public static void main(String[] args) {
//BiFunction to calculate sum of two numbers
BiFunction<Integer, Integer, Integer> biFunctionSum = (x, y) -> x + y;
//Function takes a number and multiplies is by 2
Function<Integer, Integer> biFunctionDouble = (x) -> x * 2;
// Example of andThen() method
//First biFunctionSum result is calculated (2+3)
//and then biFunctionDouble operation is performed (5*2)
Integer result = biFunctionSum.andThen(biFunctionDouble).apply(2,3);
System.out.println("result: " + result);
}
}
Output
result: 10
