BiConsumer Interface in Java with Examples
In Java, the BiConsumer interface is a functional interface that represents an operation that accepts two input arguments and performs some action with them. It takes in two arguments of different types and does not return any value. The BiConsumer interface is part of the java.util.function package introduced in Java 8 and can be used in various functional programming scenarios. The BiConsumer interface has a single method called accept() which takes two arguments and performs the desired operation.
Example 1
The above code demonstrates how the BiConsumer interface can be used to perform a specific action, such as calculating the product of two integers, by defining the action within the lambda expression passed to the BiConsumer.
FileName: BiConsumerExample.java
pre
import java.util.function.BiConsumer;
public class BiConsumerExample {
public static void main(String[] args) {
// Creating a BiConsumer to calculate the product of two integers
BiConsumer
int product = a * b;
System.out.println("The product of " + a + " and " + b + " is: " + product);
};
// Calling the BiConsumer with arguments
calculateProduct.accept(5, 6);
}
}
Output
The product of 5 and 6 is: 30
Example 2
The above code demonstrates how the BiConsumer interface can be used to perform an action on each entry of a map, such as printing the student's name and their grade, by defining the action within the lambda expression passed to the BiConsumer.
FileName: BiConsumerExample2.java
import java.util.HashMap; import java.util.Map; import java.util.function.BiConsumer; public class BiConsumerExample2 { public static void main(String[] args) { // Creating a map to store student names and their corresponding grades MapstudentGrades = new HashMap<>(); studentGrades.put("Komal", 90); studentGrades.put("Rahul", 85); studentGrades.put("Sakshi", 95); studentGrades.put("Gauri", 80); // Creating a BiConsumer to print each student and their grade BiConsumer printGrade = (student, grade) -> System.out.println(student + " scored " + grade + " marks."); // Iterating over the map and calling the BiConsumer for each entry studentGrades.forEach(printGrade); } }
Output
Komal scored 90 marks. Rahul scored 85 marks. Gauri scored 80 marks. Sakshi scored 95 marks.
Example 3
The above code demonstrates how the BiConsumer interface can perform an action involving two input arguments, such as calculating total scores, by defining the action within the lambda expression passed to the BiConsumer.
FileName: StudentScoreCalculator.java
import java.util.HashMap; import java.util.Map; import java.util.function.BiConsumer; public class StudentScoreCalculator { public static void main(String[] args) { // Creating a map to store student names and their subject scores Map> studentScores = new HashMap<>(); // Adding subject scores for students addSubjectScore(studentScores, "Rahul", "Math", 85); addSubjectScore(studentScores, "Rahul", "Science", 90); addSubjectScore(studentScores, "Komal", "Math", 75); addSubjectScore(studentScores, "Komal", "Science", 80); addSubjectScore(studentScores, "Ram", "Math", 95); addSubjectScore(studentScores, "Ram", "Science", 88); // Printing total scores for each student printTotalScores(studentScores); } private static void addSubjectScore(Map > scoresMap, String studentName, String subject, int score) { // Creating a nested map if the student does not exist scoresMap.putIfAbsent(studentName, new HashMap<>()); // Adding subject score for the student scoresMap.get(studentName).put(subject, score); } private static void printTotalScores(Map > scoresMap) { // Creating a BiConsumer to calculate and print total scores for each student BiConsumer > calculateTotalScore = (studentName, subjectScores) -> { int totalScore = 0; for (int score : subjectScores.values()) { totalScore += score; } System.out.println(studentName + " - Total Score: " + totalScore); }; // Iterating over the map and calling the BiConsumer for each student scoresMap.forEach(calculateTotalScore); } }
Output
Komal - Total Score: 155 Rahul - Total Score: 175 Ram - Total Score: 183
Example 4
The above code demonstrates how the BiConsumer interface can perform an action involving two input arguments, such as validating user credentials, by defining the action within the lambda expression passed to the BiConsumer.
FileName: UserCredentialsValidator.java
import java.util.HashMap; import java.util.Map; import java.util.function.BiConsumer; public class UserCredentialsValidator { public static void main(String[] args) { // Creating a map to store valid user credentials MapvalidCredentials = new HashMap<>(); validCredentials.put("Ram", "password123"); validCredentials.put("Rahul", "secure456"); validCredentials.put("Dev", "pass123"); // Validating user credentials validateUserCredentials(validCredentials, "Ram", "password123"); validateUserCredentials(validCredentials, "Rahul", "wrongpassword"); validateUserCredentials(validCredentials, "Dev", "pass123"); } private static void validateUserCredentials(Map credentialsMap, String username, String password) { // Creating a BiConsumer to validate user credentials BiConsumer validateCredentials = (user, pass) -> { if (credentialsMap.containsKey(user) && credentialsMap.get(user).equals(pass)) { System.out.println("Login successful for user: " + user); } else { System.out.println("Invalid credentials for user: " + user); } }; // Calling the BiConsumer with username and password validateCredentials.accept(username, password); } }
Output:
Login successful for user: Ram Invalid credentials for user: Rahul Login successful for user: Dev