Consumer Interface in Java 8 with examples

This entry is part 35 of 43 in the series Java 8 Functional Interfaces

Consumer Interface is a part of the java.util.function package which is introduced in Java 8. It is an in-built Functional Interface. This function expect an input but produces no output. In this post, we are going to see several implementations of Consumer Interface by using different examples.

Consumer_Interface_Java8_Techndeck

 

Consumer Interface in Java 8 with Examples...!!! Click To Tweet

Look at Consumer Javadoc description below:

 

 

 

 

Consumer Interface contains 2 methods:

  1. accept 

  2. andThen

 

Let’s discuss these methods:

accept 

This method accepts one input argument and performs operation on the given argument.

Syntax:

 

Below are the several examples to demonstrate accept() method:

Example 1. with Integer

 

Example 2. with HashMap

 

Example 3. with ArrayList using Stream API 

 

Example 4. with custom Class object (like ‘Students’ in this case)

 

Students Class:

 

andThen

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.

Syntax:

 

Below are the several examples to demonstrate andThen() method:

 

Example 5. with String

 

Example 6. with ArrayList using Stream API 

 

Java 8 Consumer Interface is an absolute useful addition as part of ‘Functional Interfaces’ and can serve variety of purposes. It is quite powerful as it can be used as a higher order functions through lambda functions and above examples could help you to get better idea on how to implement it.

 

Consumer Interface in Java 8 with Examples...!!! Click To Tweet

 

Do you like this Post? – then check my other helpful posts:

Other Useful References:

 

Series Navigation<< Predicate Interface in Java 8 with examplesSupplier Interface in Java 8 with examples >>

Leave a Reply

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

Facebook Twitter Instagram YouTube