Java 8 — BiFunction | Code Factory

Code Factory
2 min readMay 6, 2020

--

Index Page : Link

Reference Link : Link

Donate : Link

Normal Function can take only one input argument and perform required operation and returns the result. The result need not be boolean type.

But sometimes our programming requirement to accept 2 input values and perform required operation and should return the result. Then we should go for BiFunction.

BiFunction is exactly same as funtion except that it will take 2 input arguments.

@FunctionalInterface
public interface BiFunction<T,U,R> {
R apply(T t, U u);
default <V> BiFunction<T,U,V> andThen(Function<? super R,? extends V> after) { }
}

To find product of 2 given integers by using BiFunction :

package com.codeFactory.bifunction;import java.util.function.BiFunction;public class Test {
public static void main(String... args) {
BiFunction<Integer, Integer, Integer> f = (a, b) -> a * b;
System.out.println(f.apply(10, 20));
System.out.println(f.apply(7, 10));
}
}

Output :

200
70

Create Student Object by taking name and rollno as input by using BiFunction :

package com.codeFactory.bifunction;import java.util.ArrayList;
import java.util.function.BiFunction;
class Student {
String name;
int rollno;

Student(String name, int rollno) {
this.name = name;
this.rollno = rollno;
}
@Override
public String toString() {
return "Student [name=" + name + ", rollno=" + rollno + "]";
}
}
public class Test {
public static void main(String... args) {
ArrayList<Student> i = new ArrayList<Student>();
BiFunction<String, Integer, Student> f = (name, rollno) -> new Student(name, rollno);

i.add(f.apply("Narendra", 1));
i.add(f.apply("Amit", 2));
i.add(f.apply("Yogi", 3));
i.add(f.apply("Nitin", 4));

for(Student s : i) {
System.out.println(s);
}
}
}

Output :

Student [name=Narendra, rollno=1]
Student [name=Amit, rollno=2]
Student [name=Yogi, rollno=3]
Student [name=Nitin, rollno=4]

Calculate Monthly Salary with Employee and TimeSheet objects as input By using BiFunction :

package com.codeFactory.bifunction;import java.util.function.BiFunction;class Employee {
int eno;
String name;
double dailyWage;

Employee(int eno, String name, double dailyWage) {
this.eno = eno;
this.name = name;
this.dailyWage = dailyWage;
}
}
class TimeSheet {
int eno;
int days;

TimeSheet(int eno, int days) {
this.eno = eno;
this.days = days;
}
}
public class Test {
public static void main(String... args) {
BiFunction<Employee, TimeSheet, Double> f = (e, t) -> e.dailyWage * t.days;
Employee e = new Employee(1, "Narendra", 3000);
TimeSheet t = new TimeSheet(1, 20);
System.out.println("Monthly Salary : " + f.apply(e, t));
}
}

Output :

Monthly Salary : 60000.0

--

--