BiFunction Java 8In Java, BiFunction is a functional interface. It was introduced in Java 8. It can be used as an assignment target for a lambda expression or method reference. It belongs to java.util.function package. The interface accepts three type-parameters are as follows: T: It denotes the first argument to the function. U: It denotes the second argument to the function. R: It denotes the result of the function. T, U, and R are the descriptor that can be represented as (T, U)->R. BiFunction Interface MethodsThe interface has the following two methods:
BiFunction apply() MethodThe apply() method performs the operation on the given arguments and returns the function result. Syntax: Parameters: t: It represents the first function argument. u: It represents the second function argument. Returns: It returns the function result. ExampleBiFunctionApplyExample.java Output: The sum of x and y is: 35 BiFunction andThen() MethodIt returns a composed function. It means the method first applies this function and then applies the after function. If the assessment of either function throws an exception, it is relayed to the caller of the composed function. Syntax: Type-Parameter: V: It represents the type of the output of the after() function, and of the composed function. Parameters: after: It applies after this function. Returns: It returns a composed function. It means the method first applies this function and then applies the after function. The method throws a NullPointerException if after is null. ExampleBiFunctionAndThenExample.java Output: The result is: 350 Let's implement the above two methods in a Java program and understand the working of BiFunction interface. BiFinction ExampleBiFunctionExample1.java Output: 46 576 In the above program, the statement System.out.println(f1.andThen(f2).apply(2, 3)); can be written as follows: Integer r1 = f1.apply(11, 13); Integer r2 = f2.apply(r1); System.out.println(r2); //returns and print 576 Let's see another example. BiFunctionExample2.java Output: [Key=1, Olivia(1)] [Key=2, Noah(2)] [Key=3, John(1)] [Key=4, Alex(1)] [Key=5, Emma(1)] [Key=6, Amelia(1)] [Key=7, Noah(2)]
Next TopicEquidigital Number in Java
|