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

How to Build SaaS Product? Tips and Tricks

Selecting all But the First Custom Element

Improving Code Coverage In Android App

Scrum vs Kanban

What is a BMP file?

你好,李焕英 完整版本 完整版觀看電影在線小鴨 2021

Everything , Everywhere

A small extension for Foundation, making development easier

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

Java 13 Features

Java Post — Immutable Strings

The Java Library