What is BiConsumer in Java?

BiConsumer represents an operation that accepts two arguments and returns no value. The BiConsumer interface is a part of the java.util.function package that was introduced in Java 8. The BiConsumer interface contains two methods:

  • accept: This method executes operation on the given arguments.
  • andThen: This method takes a BiConsumer as an argument that will be executed after the current one.

Using the accept method

import java.util.function.BiConsumer;
class Main {
public static void main( String args[] ) {
BiConsumer<String, String> printName = (firstName, lastName) -> System.out.println(firstName + lastName);
printName.accept("Educative", ".io");
}
}

In the above code, we have created a BiConsumer interface that will accept two arguments and print the value. It also doesn’t return any value.

Using the andThen method

import java.util.function.BiConsumer;
class Main {
public static void main( String args[] ) {
String name1 = "raj";
String name2 = "raj";
BiConsumer<String, String> bc1 = (n1, n2) -> {
System.out.println("Name 1 = " + n1);
System.out.println("Name 2 = " + n2);
};
BiConsumer<String, String> bc2 = (n1, n2) -> {
System.out.println("Both names are same => " + n1.equals(n2));
};
bc1.andThen(bc2).accept(name1, name2);
}
}

In the above code, we have two BiConsumers (bc1 and bc2). First, we called bc1.andThen with bc2 as an argument so that bc1 BiConsumer will be executed and return a composed BiConsumer bc2. bc2 can be executed by calling the accept method.


The BiConsumer interface can be used as an argument on a forEach loop.

import java.util.Map;
import java.util.HashMap;
import java.util.function.BiConsumer;
class Main {
public static void main( String args[] ) {
Map<Integer, String> nums = new HashMap<>();
nums.put(1, "one");
nums.put(2, "two");
nums.put(3, "three");
nums.put(4, "four");
nums.put(5, "five");
BiConsumer<Integer, String> biConsumer = null;
biConsumer = (key, val) -> {
System.out.println(key + " : " + val.toUpperCase());
};
nums.forEach(biConsumer);
}
}

In the above code, we have passed the BiConsumer interface as an argument to the forEach loop. The forEach loop will internally call the accept method for each entry on the map.

Free Resources