Java 8 Biconsumer example


Biconsumer was introduced in java 8 as part of java.util.function. It accepts 2 arguments as inputs and does not return any output.It was introduced to implement functional programming in java.


Interface BiConsumer<T,U>
Type Parameters:
T - the type of the first argument to the operation
U - the type of the second argument to the operation

Functions in BiConsumer interface:

This interface has 2 functions:

  • accept
  • andThen

Accept function

This method accepts 2 arguments.Its implementation handles logic to be performed on them and it does not return anything.

void accept(T t, U u)
Performs this operation on the given arguments.
t - the first input argument
u - the second input argument

First code example for accept function

This is a simple BiConsumer example which takes 2 strings an inputs and display them on console.Note that there is no output.

Sachin Tendulkar

Second code example for accept function

In this example , the biconsumer ‘evenCheck’ accepts 2 integers.It evaluates if both the parameters are integers are not and displays the result on console.

INPUT: arguements are 2 & 4
RESULT: Both parameters are even
INPUT: arguements are 3 & 4
Only one parameters are even
INPUT: arguements are 10 & 11
Only one parameters are even
INPUT: arguements are 11 & 13
Both parameters are not even

andThen function

This function returns a composed BiConsumer, where the Biconsumer passed to anThen() will be executed after the first one.

default BiConsumer<T,U> andThen(BiConsumer<? super T,? super U> after)
Returns a composed BiConsumer that performs, in sequence, this operation followed by the after operation. If performing either operation throws an exception, it is relayed to the caller of the composed operation. If performing this operation throws an exception, the after operation will not be performed.
after - the operation to perform after this operation
a composed BiConsumer that performs in sequence this operation followed by the after operation
NullPointerException - if after is null

Code example for BiConsumer andThen() function:

In this program , there are 2 BiConsumers. The first one ‘compareList’ compares 2 list of strings and prints the result in console.The second one ‘display’ prints both the lists on the console.

compareList.andThen(display).accept(names1, names2);

The above command first executes compareList and then display biconsumer in a sequential manner.

Both lists are equal
List1 :
List2 :

You may also like...

Leave a Reply

Your email address will not be published.