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:
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. Parameters:
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.
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.
Output: 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
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
BiConsumerthat performs, in sequence, this operation followed by the
afteroperation. 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
afteroperation will not be performed. Parameters:
after- the operation to perform after this operation Returns: a composed
BiConsumerthat performs in sequence this operation followed by the
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.
The above command first executes compareList and then display biconsumer in a sequential manner.
Both lists are equal List1 : Sachin Lara Waugh Gavaskar List2 : Sachin Lara Waugh Gavaskar