Java 8 Consumer example

Java 8 Consumer
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:

Student [id=1, name=Arpit, gender=M, age=19] Student [id=2, name=John, gender=M, age=17] Student [id=3, name=Mary, gender=F, age=14] Student [id=4, name=Martin, gender=M, age=21] Student [id=5, name=Monica, gender=F, age=16] Student [id=6, name=Ally, gender=F, 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.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *