Java 8 — BiConsumer | Code Factory

@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");
}
}
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);
}
}
}
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]

Comparison Table between One argument and Two argument Functional Interfaces :

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Modular iOS Part 3: Configuration & Testing of Modules

Raise your hand if you want to quit drinking coffee. Why, though???

The IntelliGrator!

From Documenting to Thinking and Designing to Doing: Metacognitive Tools and Data-driven…

Minikube in Hyper-V with nested virtualization

How to Annotate Barcode Object with LabelImg for Machine Learning

Additional features of BestChange

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Code Factory

Code Factory

More from Medium

Singleton(s) in Java

Single Responsibility Principle (SRP)

Chain Of Responsibility Design Pattern

What is java?