🚀 Introduction to Java BiConsumer
Functional Interface
In Java functional programming, the BiConsumer<T, U>
interface (from java.util.function
) is a functional interface that takes two input arguments and performs an action without returning a result.
✅ T (First Input Type): The type of the first argument.
✅ U (Second Input Type): The type of the second argument.
✅ Return Type: void
– The function executes an operation but does not return a value.
💡 Common Use Cases:
✔ Logging and printing — Displaying messages using two inputs.
✔ Processing and updating data — Storing and modifying values without returning anything.
✔ Performing calculations — Processing numerical inputs and printing results.
📌 In this article, you’ll learn:
✅ How to use BiConsumer<T, U>
with examples.
✅ How to use accept()
to process values.
✅ How to chain multiple BiConsumer
functions using andThen()
.
✅ Real-world use cases where BiConsumer
improves Java applications.
1️⃣ Using accept()
to Process Two Inputs
The accept(T t, U u)
method performs an operation on the given inputs.
✔ Example: Printing a Full Name
import java.util.function.BiConsumer;
public class BiConsumerExample {
public static void main(String[] args) {
// ✅ BiConsumer to print first name and last name
BiConsumer<String, String> printFullName = (firstName, lastName) ->
System.out.println("Full name: " + firstName + " " + lastName);
printFullName.accept("Ramesh", "Fadatare");
// Output: Full name: Ramesh Fadatare
}
}
📌 Why use BiConsumer
for printing names?
✅ Encapsulates the logic into a reusable function.
✅ Improves modularity and avoids repetitive System.out.println()
calls.
🚀 Use BiConsumer.accept()
when processing two inputs without returning a value!
2️⃣ Printing Email and Password Using BiConsumer
✔ Example: Displaying Email and Password Securely
import java.util.function.BiConsumer;
public class BiConsumerExample {
public static void main(String[] args) {
// ✅ BiConsumer to print email and password
BiConsumer<String, String> printEmailPassword = (email, password) -> {
System.out.println("Email: " + email);
System.out.println("Password: " + password);
};
printEmailPassword.accept("ramesh@gmail.com", "ramesh_secret");
// Output:
// Email: ramesh@gmail.com
// Password: ramesh_secret
}
}
📌 Why use BiConsumer
for handling credentials?
✅ Encapsulates credential handling logic in one place.
✅ Prevents repetitive code in different parts of the application.
🚀 Use BiConsumer
for handling input-based tasks like logging in a structured way!
3️⃣ Combining BiConsumer
Functions Using andThen()
The andThen()
method allows chaining multiple BiConsumer
functions sequentially.
✔ Example: Printing Numbers and Then Calculating Their Sum
import java.util.function.BiConsumer;
public class AndThenBiConsumerExample {
public static void main(String[] args) {
// ✅ BiConsumer to print two numbers
BiConsumer<Integer, Integer> printNumbers = (num1, num2) ->
System.out.println("Numbers: " + num1 + ", " + num2);
// ✅ BiConsumer to add two numbers and print the sum
BiConsumer<Integer, Integer> addNumbers = (num1, num2) ->
System.out.println("Sum: " + (num1 + num2));
// ✅ Chain BiConsumer functions using andThen()
BiConsumer<Integer, Integer> printAndAdd = printNumbers.andThen(addNumbers);
printAndAdd.accept(7, 8);
// Output:
// Numbers: 7, 8
// Sum: 15
}
}
📌 Why use andThen()
?
✅ Allows multiple actions to be performed on the same inputs.
✅ Improves code organization and modularity.
🚀 Use andThen()
to chain multiple processing steps efficiently!
4️⃣ Real-World Use Cases of BiConsumer
Interface
✔ Use Case 1: Logging API Requests
import java.util.function.BiConsumer;
public class ApiLogger {
public static void main(String[] args) {
// ✅ BiConsumer to log request details
BiConsumer<String, String> logRequest = (endpoint, status) ->
System.out.println("API Endpoint: " + endpoint + " | Status: " + status);
logRequest.accept("/api/users", "200 OK");
// Output: API Endpoint: /api/users | Status: 200 OK
}
}
📌 Why use BiConsumer
for logging API calls?
✅ Encapsulates request logging logic in a reusable function.
✅ Prevents duplicate logging statements throughout the application.
🚀 Use BiConsumer
for logging API interactions in a structured way!
✔ Use Case 2: Updating a User Profile
import java.util.function.BiConsumer;
class User {
String name;
int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
public void updateProfile(String newName, int newAge) {
this.name = newName;
this.age = newAge;
System.out.println("Updated User: " + name + ", Age: " + age);
}
}
public class UserProfileUpdater {
public static void main(String[] args) {
User user = new User("Ramesh", 30);
// ✅ BiConsumer to update user profile
BiConsumer<User, String> updateUserName = (u, newName) -> u.name = newName;
BiConsumer<User, Integer> updateUserAge = (u, newAge) -> u.age = newAge;
// ✅ Update the user profile
updateUserName.andThen(updateUserAge).accept(user, "Amit");
updateUserAge.accept(user, 35);
System.out.println("Final User Profile: " + user.name + ", Age: " + user.age);
}
}
📌 Why use BiConsumer
for updating objects?
✅ Encapsulates profile update logic into separate functions.
✅ Easily chainable to perform multiple updates at once.
🚀 Use BiConsumer
for modifying objects dynamically without returning values!
🔥 Best Practices for Using BiConsumer
Functional Interface

BiConsumer
Functional Interface🔑 Key Takeaways
✅ The BiConsumer<T, U>
interface processes two inputs without returning a value.
✅ Use accept()
to execute actions based on two input values.
✅ Use andThen()
to chain multiple BiConsumer
functions sequentially.
✅ Apply BiConsumer
in real-world cases like logging API requests and updating user profiles.
By mastering the BiConsumer
functional interface, your Java code will be more modular, efficient, and structured! 🚀
Comments
Post a Comment
Leave Comment