Java Bifunction example


BiFunction was introduced in java 8 as part of java.util.function. It accepts 2 arguments as inputs and returns an output. It was introduced to implement functional programming in java.


Interface BiFunction<T,U,R>
Type Parameters:
T - the type of the first argument to the function
U - the type of the second argument to the function
R - the type of the result of the function

Functions of BiFunction interface

This interface has 2 functions:

  • apply
  • andThen

Apply Function:

java bifunction has apply method which takes 2 parameters as inputs, handles the computational logic and returns an output.

R apply(T t, U u)
Applies this function to the given arguments.
t - the first function argument
u - the second function argument
the function result

Code example for apply function:

In the below code example , I have created 4 Bi-functions for different arithmetic operations.Each function takes 2 integer inputs and returns an integer output.


The apply method is responsible to pass the input parameters to the bi-Function.

package com.ppkcodes;

import java.util.function.BiFunction;

 * This class shows how to implement a BiFunction for simple arithmetic operations
public class BiFunctionExample {

  public static void main(String[] args) {
    BiFunction<Integer,Integer,Integer> add=(i,j)->i+j;
    BiFunction<Integer,Integer,Integer> subtract=(i,j)->i-j;
    BiFunction<Integer,Integer,Integer> multiply=(i,j)->i*j;
    BiFunction<Integer,Integer,Integer> devide=(i,j)->i/j;

    System.out.println("Addtion "+add.apply(1,2));
    System.out.println("Subtraction "+subtract.apply(5,2));
    System.out.println("Multiplication "+multiply.apply(5,2));
    System.out.println("Division "+devide.apply(10,2));
Addtion 3
Subtraction 3
Multiplication 10
Division 5

You may also like...

Leave a Reply

Your email address will not be published.