Java 8 — BiFunction | Code Factory

@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));
}
}
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);
}
}
}
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));
}
}
Monthly Salary : 60000.0

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store