Java 8 — BiConsumer | Code Factory
2 min readMay 7, 2020
Index Page : Link
Reference Link : Link
Donate : Link
Normal Consumer can take only one input argument and perform required operation and won’t return any result.
But sometimes our programming requirement to accept 2 input values and perform required operation and not required to return any result. Then we should go for BiConsumer.
BiConsumer is exactly same as Consumer except that it will take 2 input arguments.
@FunctionalInterface
public interface BiConsumer<T,U> {
void accept(T t, U u);
default BiConsumer<T,U> andThen(BiConsumer<? super T,? super U> after) { }
}
Program to accept 2 String values and print result of concatenation by using BiConsumer :
package com.codeFactory.biconsumer;import java.util.function.BiConsumer;public class Test {
public static void main(String... args) {
BiConsumer<String, String> c = (s1, s2) -> System.out.println(s1 + s2);
c.accept("Code", "Factory");
}
}
Output :
CodeFactory
Demo Program to increment employee Salary by using BiConsumer :
package com.codeFactory.biconsumer;import java.util.ArrayList;
import java.util.function.BiConsumer;class Employee {
String name;
double salary;
Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}@Override
public String toString() {
return "Employee [name=" + name + ", salary=" + salary + "]";
}}public class Test {
public static void main(String... args) {
ArrayList<Employee> i = new ArrayList<>();
populate(i);
System.out.println("Before Increment :");
print(i);
BiConsumer<Employee, Double> c = (e, d) -> e.salary += d;
for(Employee e : i) {
c.accept(e, 750.0);
}
System.out.println("After Increment :");
print(i);
}
private static void populate(ArrayList<Employee> i) {
i.add(new Employee("Narendra", 1000));
i.add(new Employee("Amit", 2000));
i.add(new Employee("Vijay", 3000));
i.add(new Employee("Yogi", 4000));
}
private static void print(ArrayList<Employee> i) {
for(Employee e : i) {
System.out.println(e);
}
}
}
Output :
Before Increment :
Employee [name=Narendra, salary=1000.0]
Employee [name=Amit, salary=2000.0]
Employee [name=Vijay, salary=3000.0]
Employee [name=Yogi, salary=4000.0]
After Increment :
Employee [name=Narendra, salary=1750.0]
Employee [name=Amit, salary=2750.0]
Employee [name=Vijay, salary=3750.0]
Employee [name=Yogi, salary=4750.0]