What is Bi-Consumer interface ?
Bi-Consumer interface is one of the functional interfaces that Java 8 provides. It is present in java.util.function package.
It is quite similar to consumer interface, just that it accepts two parameters.
@FunctionalInterface
public interface BiConsumer<T,U>
Since it is a functional interface it has only one method definition . That method is called Accept.
We all know functional interfaces can have default methods also . So here we have a default method called andThen .
What are the methods of the Bi-Consumer interface ?
Accept :
void accept(T t,U u)
The accept method accepts two input parameter and performs a user defined operation on them.
AndThen :
default BiConsumer<T,U> andThen(BiConsumer<? super T,? super U> after)
The andThen method takes in a Bi-Consumer as an input and it runs it after the Bi-Consumer it is called upon.
Let us look at few examples !!!!!!
First lets look at the example of accept method . It accepts two values and performs given operation on them .
Class BiConsumerExample{
public static void main(String[] args){
BiConsumer<String,String> consumer= (s,s1)->System.out.println(s+"
"+s1);
consumer.accept("Hello","World");
}
}
o/p = Hello World
Now let us look at an example of the andThen method of the BiConsumer interface.
Class BiConsumerExample{
public static void main(String[] args){
BiConsumer<String,String> consumer1= (s,s1)->System.out.println(s+" "+s1);
BiConsumer<String,String> consumer2= (s2,s3)->System.out.println(
s2.toUpperCase(),s3.toUpperCase());
consumer1.andThen(consumer2).accept("Hello","World");
}
}
o/p :
Hello World
HELLO WORLD
Let us look at above example.
First we are creating one consumer called consumer1 which takes in two strings and just prints them.
Next we are creating one more consumer called consumer2 which takes in two string converts the strings to uppercase and then prints the strings.
Next we want to make consumer1 run first and then we want to make consumer2 run.
So we do consumer1.andThen(consumer2)
which achieves that .
Next we need to pass some input to perform this operation so we make use of accept method of consumer as below .
consumer1.andThen(consumer2).accept("Hello","World");
Note: Kindly correct me in any info that is wrong on above blog . I am happy to learn .
Also kindly have a look at my blog :)
[https://praveen075.blogspot.com/2021/04/introduction-to-java-8-in-laymans-terms_13.html]
Thank you
Top comments (0)