BiFunction Interface is a part of the java.util.function package which is introduced in Java 8. It is an in-built Functional Interface. This function expect two arguments as an input and produces a result. As it is a functional interface, it can be used assignment target for lambda expression or method reference. In this post, we are going to see several implementations of BiFunction Interface by using different examples.
BiFunction Interface in Java 8 with Examples...!!! Share on X
Look at BiFunction Javadoc description below:
BiFunction Interface contains 2 methods:
apply
andThen
Let’s discuss these methods:
apply
This method performs operation on the given arguments and return the function result.
1 | R apply(T t, U u); |
andThen
This method returns a composed function that first applies this function to its input, and then applies the after function to the result. If evaluation of either function throws an exception, it is relayed to the caller of the composed function.
1 2 3 4 | default <V> BiFunction<T, U, V> andThen(Function<? super R, ? extends V> after) { Objects.requireNonNull(after); return (T t, U u) -> after.apply(apply(t, u)); } |
Lets understand above mentioned methods thorough various examples:
Example 1. ‘apply’ method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import java.util.function.BiFunction; public class BiFunctionInterfaceJava8Example1 { public static void main(String[] args) { System.out.println("BiFunction Interface - 'apply' example \n"); BiFunction <Integer, Integer, Integer> biFunctionObj = (i1, i2) -> i1 + i2; System.out.println("Sum of 2 integer values 5 and 8 is: " + biFunctionObj.apply(5, 8)); } } |
Example 2. ‘andThen’ methods
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | import java.util.function.BiFunction; import java.util.function.Function; public class BiFunctionInterfaceJava8Example2 { public static void main(String[] args) { System.out.println("BiFunction Interface - 'andThen' example \n"); BiFunction <Integer, Integer, Integer> biFunctionObj = (i1, i2) -> i1 * i2; Function <Integer, Integer> functionObj = (i) -> i / 2; System.out.println("Sum of 2 integer values 5 and 8 is: " + biFunctionObj.andThen(functionObj).apply(10, 5)); } } |
BiFunction Interface in Java 8 with Examples...!!! Share on X
Do you like this Post? – then check my other helpful posts:
- Passing Function as a Parameter in another Method in Java 8
- Collection sorting using Lambda in Java 8
- Supplier Interface in Java 8 with Examples