Java 8 Consumer example

Previous
Next

In this post, we are going to see about java 8 Consumer interface.
Consumer is single argument functional interface like Predicate but it does not return any value. As Consumer is functional interface, so it can be used as assignment target for lambda expressions.

Consumer definition

Consumer takes single argument and do not return any result.
Here is the definition of Consumer interface.

It has a functional method called accept() and default method andThen().

Consumer examples

accept() method example

Let’s use Consumer interface to print String:

We have created consumer object which takes String object as input and print it.It is simple use of Consumer interface to print String.
When you run above program, you will get below output:

Arpit

default andThen() method example

As per java docs:
Returns a composed Consumer that performs, in sequence, this operation followed by the after operation. 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 after operation will not be performed.

Output:

arpit
ARPIT

As you can see, we have created two consumers and used andThen() method to create composite consumer. When we called accept() method on composite consumer, both the consumers are called in sequence.

Consumer foreach example

Let’s say you have Student class as below:

Now let’s create Consumer object in main class and pass it to forEach method of list:

When you run above program, you will get below output:

name : Arpit == Age : 19
name : John == Age : 17
name : Mary == Age : 14
name : Martin == Age : 21
name : Monica == Age : 16
name : Ally == Age : 20

We have created consumer object which takes student object as input and print it.Above created consumer object is then passed to foreach() method of Iterable interface.

As you can see, foreach() method takes consumer as input and calls accept() method on each object of Iterable.
That’s all about Java 8 consumer example.

Previous
Next

Add Comment