Consumer Interface
What is consumer interface ?
Consumer interface is one of the functional interfaces that Java 8 provides. It is present in java.util.function package.
@FunctionalInterface
public interface consumer<T>
Let us look at some of the important points about the consumer interface below.
- Consumer interface is a functional interface that is it only has on method definition and that method is called the accept . It takes in only one parameter and does not return anything as the output.
- We also know that functional interfaces can have method of default scope also that is default methods. Well Consumer interface also has one default method know as andThen which takes in a consumer as input parameter.
Let us look at few examples !!!
Let us first look at how to give a input to the consumer interface and perform an operation. For giving an input to the consumer interface we can make use of the accept method as shown below .
Class ConsumerExample{
public static void main(String[] args){
Consumer<String> consumer= (s)->System.out.println(s);
consumer.accept("Example test");
}
}
o/p = Example test
Let us understand what we are doing in above example. We are creating an Consumer interface of string type. Then we are using lambda expression to pass a string as input to the accept method and we are defining the body of the accept method to print the passed string .
If you are finding it difficult to understand Lambda expression then please refer to the link below .
https://praveen075.blogspot.com/2021/04/introduction-to-java-8-in-laymans-terms.html
Now let us look at another example where we make use of andThen method to call one consumer after another.
Class ConsumerExample{
public static void main(String[] args){
Consumer<String> consumer1= (s)->System.out.println(s);
Consumer<String> consumer2= (s)->System.out.println(s.toUpperCase());
consumer1.andThen(consumer2).accept("Example test");
}
}
o/p :
Example test
EXAMPLE TEST
Let us look at above example.
First we are creating one consumer called consumer1 which takes in a string and just prints it.
Next we are creating one more consumer called consumer2 which takes in a string converts the string to uppercase and then prints the string.
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("Example test")
Note: Kindly correct me in any info that is wrong on above blog . I am happy to learn .
Comments
Post a Comment