Java BiFunction

📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.

🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.

▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube

▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube

Introduction

In Java, the BiFunction interface is a functional interface that represents a function which takes two arguments and produces a result. It is part of the java.util.function package and is commonly used for operations where two input parameters need to be processed to produce a single output.

Table of Contents

  1. What is BiFunction?
  2. Methods and Syntax
  3. Examples of BiFunction
  4. Real-World Use Case
  5. Conclusion

1. What is BiFunction?

BiFunction is a functional interface that takes two arguments and returns a result. It is often used in lambda expressions and method references to handle operations involving two parameters and producing a single output.

2. Methods and Syntax

The main method in the BiFunction interface is:

  • R apply(T t, U u): Applies this function to the given arguments and returns a result.

Syntax

BiFunction<T, U, R> biFunction = (T t, U u) -> { // operation on t and u return result; }; 

3. Examples of BiFunction

Example 1: Adding Two Numbers

import java.util.function.BiFunction; public class BiFunctionExample { public static void main(String[] args) { // Define a BiFunction that adds two integers BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b; Integer result = add.apply(5, 3); System.out.println("Sum: " + result); } } 

Output:

Sum: 8 

Example 2: Concatenating Two Strings

import java.util.function.BiFunction; public class BiFunctionStringExample { public static void main(String[] args) { // Define a BiFunction that concatenates two strings BiFunction<String, String, String> concatenate = (str1, str2) -> str1 + str2; String result = concatenate.apply("Hello, ", "World!"); System.out.println(result); } } 

Output:

Hello, World! 

4. Real-World Use Case: Calculating Discounts

In e-commerce applications, BiFunction can be used to calculate the final price of an item after applying a discount.

import java.util.function.BiFunction; public class DiscountCalculator { public static void main(String[] args) { // Define a BiFunction to calculate the price after discount BiFunction<Double, Double, Double> calculateDiscount = (price, discount) -> price - (price * discount / 100); Double originalPrice = 100.0; Double discount = 15.0; Double finalPrice = calculateDiscount.apply(originalPrice, discount); System.out.println("Final Price: " + finalPrice); } } 

Output:

Final Price: 85.0 

Example: Combining Two Maps

In some scenarios, you might need to combine two maps into one using a specific merging strategy. Here's an example of how BiFunction can help in this situation:

import java.util.HashMap; import java.util.Map; import java.util.function.BiFunction; public class MapCombiner { public static void main(String[] args) { // Define two maps with product quantities from different stores Map<String, Integer> store1 = new HashMap<>(); store1.put("Apple", 50); store1.put("Banana", 30); Map<String, Integer> store2 = new HashMap<>(); store2.put("Apple", 20); store2.put("Banana", 25); store2.put("Orange", 10); // Define a BiFunction to merge the quantities of the products BiFunction<Integer, Integer, Integer> mergeQuantities = (qty1, qty2) -> qty1 + qty2; // Combine the maps store2.forEach((key, value) -> store1.merge(key, value, mergeQuantities)); System.out.println(store1); } } 

Output:

{Apple=70, Banana=55, Orange=10} 

Conclusion

The BiFunction interface is used in Java for processing operations that require two inputs to produce a single output. It is particularly useful in scenarios like mathematical computations, string manipulations, and data processing tasks. Using BiFunction can lead to more concise and readable code, especially when working with functional programming paradigms.

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