Consumer Functional Interface in Java

Consumer Functional Interface:- 

Consumer is an in-built functional interface which can be used in all contexts where an object needs to be consumed.

In other words, we can say that Consumer is used where some object is to be taken as input, some operation is to be performed on the object but we don’t want any return value.

Common example of such an operation is printing where an object is taken as input to the printing function and the value of the object is printed.

Consumer functional interface members:-

1) The Consumer interface has a SAM called accept().
2) It accepts an object of any data type and returns nothing.
3) Consumer contains 2 methods and they are:-

    a. accept( )
    b. and Then( )

4) The method accept( ) is an abstract method while andThen( ) is default method.

Prototype of accept( ):- Following is the complete prototype of the method accept( ) as declared in the interface Consumer.

        public interface Consumer<T>  {
                    public void apply( T parameter);
        }

As we can observe the method accept() accepts an argument of type and returns nothing.

Example:-

A Consumer to double the value of each member of the List passed to it as argument and another Consumer to display the List passed to it as argument.


Output:-
Before doubling:
10 20 30 40 50
After doubling:
20 40 60 80 100

Consumer chaining:-

Java allows us to join two or more Consumers also.
This can be done by calling the default method called andThen() given by Consumer functional interface.

Prototype of andThen( ):-

     default Consumer <T> andThen(Consumer <T> after);

The method andThen( ) returns a composed Consumer that performs in sequence, this operation followed by the after operation.
Ex:-
        c3=c1.andThen(c2);

The above code will create a new Consumer called c3 and when we will call accept() on it , then it will first call c1.accept() and then c2.accept() with the argument passed.

Example:-

Output:-

Before doubling:
10 20 30 40 50
After doubling:
20 40 60 80 100


Post a Comment

0 Comments