Introduction
In this blog we will learn how to use Consumer functional interface in java.util.Function
.
Consumer as the name suggest will consume whatever is sent across and will not return anything.
Consumer<T>
accepts the argument and perform operations on it but do not return anything.
Consumer<T>
functional method is void accept(T t)
.
In the below example we can see Consumer interface accepts a integer and prints it , without returning anything.
Consumer example 1:
|
|
|
|
We can write same code using lambda expresssion.
|
|
Consumer example 2
In the below example we can accept list as an argument in Consumer interface.
|
|
|
|
Composed Consumer
We can chain multiple consumer of the same type together to perform operations in sequence.
We can perform this using andThen() method which returns a composed Consumer that performs, in sequence, this operation followed by the after operation
|
|
In the below example we define 2 consumers.
First one just prints the number consumed
Second consumes and increments the number.
We create composed consumer and pass a number.
It performs operation in sequence and prints 100 and 101.
|
|
BiConsumer
BiConsumer<T,U> is similar to Consumer, but here it accepts 2 arguments. For some use cases we may want to accept 2 argument and perform operations on them.
Functional method signature is as follows
|
|
In the below example , we accept 2 Integer arguments and print the sum of those numbers.
|
|
Conclusion
I hope this tutorial has helped you to get started with Consumer Interface
in Java.