Javatpoint Logo
Javatpoint Logo

BiFunction Java 8

In 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 Methods

The interface has the following two methods:

  • apply()
  • andThen()

BiFunction apply() Method

The 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.

Example

BiFunctionApplyExample.java

Output:

The sum of x and y is: 35 

BiFunction andThen() Method

It 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.

Example

BiFunctionAndThenExample.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 Example

BiFunctionExample1.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)]   






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA