Java BiFunction Functional Interface with Real-World Examples

🚀 Introduction to Java BiFunction Functional Interface

In Java functional programming, the BiFunction<T, U, R> interface (from java.util.function) is a functional interface that takes two input arguments and returns a result.

T (First Input Type): The type of the first argument.
 ✅ U (Second Input Type): The type of the second argument.
 ✅ R (Return Type): The type of the result.

💡 Common Use Cases:
 ✔ Performing calculations — Addition, subtraction, multiplication, and division.
 ✔ Processing two inputs — Combining two values into one result.
 ✔ Transforming and mapping values — Applying a transformation based on two inputs.

📌 In this article, you’ll learn:
 ✅ How to use BiFunction<T, U, R> with examples.
 ✅ How to use apply() to process values.
 ✅ How to chain BiFunction with Function using andThen().
 ✅ Real-world use cases where BiFunction improves Java applications.

1️⃣ Using apply() to Perform Arithmetic Operations

The apply(T t, U u) method processes two inputs and returns a result.

✔ Example: Performing Basic Arithmetic Operations

import java.util.function.BiFunction;

public class BiFunctionExample {
public static void main(String[] args) {
// ✅ BiFunction to add two numbers
BiFunction<Integer, Integer, Integer> addition = (num1, num2) -> num1 + num2;
int result = addition.apply(10, 20);
System.out.println("Addition: " + result); // Output: Addition: 30

// ✅ BiFunction to subtract two numbers
BiFunction<Integer, Integer, Integer> subtraction = (num1, num2) -> num1 - num2;
int result1 = subtraction.apply(20, 10);
System.out.println("Subtraction: " + result1); // Output: Subtraction: 10

// ✅ BiFunction to multiply two numbers
BiFunction<Integer, Integer, Integer> multiplication = (num1, num2) -> num1 * num2;
int result2 = multiplication.apply(20, 10);
System.out.println("Multiplication: " + result2); // Output: Multiplication: 200

// ✅ BiFunction to divide two numbers
BiFunction<Integer, Integer, Integer> division = (num1, num2) -> num1 / num2;
int result3 = division.apply(20, 10);
System.out.println("Division: " + result3); // Output: Division: 2
}
}

📌 Why use BiFunction for arithmetic operations?
 ✅ Encapsulates mathematical operations into reusable functions.
 ✅ Provides a flexible way to perform calculations with two inputs.

🚀 Use BiFunction<T, U, R> when working with operations that require two inputs!

2️⃣ Using andThen() to Transform Results

The andThen(Function<R, V>) method allows chaining a BiFunction with a Function for further transformation.

✔ Example: Multiplying Two Numbers and Converting the Result to a String

import java.util.function.BiFunction;
import java.util.function.Function;

public class AndThenBiFunctionExample {
public static void main(String[] args) {
// ✅ BiFunction to calculate the product of two numbers
BiFunction<Integer, Integer, Integer> multiplyNumbers = (num1, num2) -> num1 * num2;

// ✅ Function to convert the result to a string
Function<Integer, String> convertToString = num -> "Product: " + num;

// ✅ Chain BiFunction and Function using andThen()
BiFunction<Integer, Integer, String> multipleAndConvert = multiplyNumbers.andThen(convertToString);

String result = multipleAndConvert.apply(5, 4);
System.out.println(result); // Output: Product: 20
}
}

📌 Why use andThen()?
 ✅ Allows multiple transformations in a single step.
 ✅ Improves readability and modularity.

🚀 Use andThen() to process and transform results efficiently!

3️⃣ Using BiFunction to Calculate Rectangle Area

✔ Example: Calculating the Area of a Rectangle

import java.util.function.BiFunction;

public class RectangleAreaBiFunctionExample {
public static void main(String[] args) {
// ✅ BiFunction to calculate the area of a rectangle
BiFunction<Integer, Integer, Integer> calculateArea = (length, width) -> length * width;

int area = calculateArea.apply(5, 4);
System.out.println("Area of rectangle: " + area); // Output: Area of rectangle: 20
}
}

📌 Why use BiFunction for geometric calculations?
 ✅ Encapsulates the logic for computing an area.
 ✅ Reusability in applications dealing with geometry and measurements.

🚀 Use BiFunction when working with formulas that take two inputs!

4️⃣ Real-World Use Cases of BiFunction Interface

✔ Use Case 1: Combining First Name and Last Name

import java.util.function.BiFunction;

public class FullNameExample {
public static void main(String[] args) {
// ✅ BiFunction to concatenate first and last names
BiFunction<String, String, String> fullName = (firstName, lastName) -> firstName + " " + lastName;

String name = fullName.apply("Amit", "Sharma");
System.out.println("Full Name: " + name); // Output: Full Name: Amit Sharma
}
}

📌 Why use BiFunction for name concatenation?
 ✅ Improves readability and modularity.
 ✅ Avoids manual string concatenation everywhere.

🚀 Use BiFunction when combining two strings dynamically!

✔ Use Case 2: Calculating Employee Salary Based on Hours Worked

import java.util.function.BiFunction;

class Employee {
String name;
double hourlyRate;

public Employee(String name, double hourlyRate) {
this.name = name;
this.hourlyRate = hourlyRate;
}
}

public class SalaryCalculator {
public static void main(String[] args) {
// ✅ BiFunction to calculate salary based on hours worked
BiFunction<Employee, Integer, Double> calculateSalary =
(employee, hoursWorked) -> employee.hourlyRate * hoursWorked;

Employee emp = new Employee("Ramesh", 50.0);
double salary = calculateSalary.apply(emp, 40);
System.out.println("Salary: $" + salary); // Output: Salary: $2000.0
}
}

📌 Why use BiFunction for salary calculation?
 ✅ Encapsulates salary computation logic into a reusable function.
 ✅ Ensures cleaner and maintainable payroll calculations.

🚀 Use BiFunction for financial calculations based on two parameters!

🔥 Best Practices for Using BiFunction Functional Interface

Best Practices for Using BiFunction Functional Interface

🔑 Key Takeaways

The BiFunction<T, U, R> interface processes two inputs and returns a result.
 ✅ Use apply() for performing operations on two values.
 ✅ Use andThen() to transform the output of a BiFunction.
 ✅ Apply BiFunction in real-world cases like salary calculation and name concatenation.

By mastering the BiFunction functional interface, your Java code will be more modular, efficient, and structured! 🚀

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare