Core Java

Java 8 Consumer and Supplier Example

Photo of YatinYatinJanuary 12th, 2018Last Updated: February 25th, 2019
2 1,165 5 minutes read

Hello readers, this tutorial explains the in-built functional interfaces (i.e.Consumer<T> andSupplier<T>) introduced in Java8.

1. Introduction

These features are the functional interfaces (i.e. an interface with only one abstract method) which belongs to thejava.util.function package.
 
 
 
 
 

1.1 What is Consumer?

Consumer<T> is an in-built functional interface introduced in Java8 in thejava.util.function package. The consumer can be used in all contexts where an object needs to be consumed, i.e. taken as an input and some operation is to be performed on the object without returning any result. A 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. SinceConsumer is a functional interface, hence it can be used as the assignment target for a lambda expression or a method reference.

1.1.1 Function Descriptor of Consumer<T>

Consumer’s function descriptor isT -> (). This means an object of type “T” is input to the lambda with no return value. Let’s see the source code that follows this implementation.

@FunctionalInterfacepublic interface Consumer<T> {    void accept(T t);    default Consumer<T> andThen(Consumer<? super T> after) {        Objects.requireNonNull(after);        return (T t) -> { accept(t); after.accept(t); };    }}

1.1.2 Advantage

In all scenarios where an object is to be taken as an input and an operation performed on it, the in-built functional interfaceConsumer<T> can be used without the need to define a new functional interface every time.

1.2 What is Supplier?

Supplier<T> is an in-built functional interface introduced in Java8 in thejava.util.function package. The supplier can be used in all contexts where there is no input but an output is expected. SinceSupplier is a functional interface, hence it can be used as the assignment target for a lambda expression or a method reference.

1.2.1 Function Descriptor of Supplier<T>

Supplier’s Function Descriptor isT -> (). This means that there is no input in the lambda definition and the return output is an object of type “T”. Let’s see the source code that follows this implementation.

@FunctionalInterfacepublic interface Supplier<T> {    /**     * Gets a result.     * @return a result     */    T get();}

1.2.2 Advantage

In all scenarios where there is no input to an operation and it is expected to return an output, the in-built functional interfaceSupplier<T> can be used without the need to define a new functional interface every time.

Now, open up the Eclipse Ide and let’s have a look at a simple code example where theConsumer andSupplier interface is being used.

2. Java8 Consumer and Supplier Example

2.1 Tools Used

We are using Eclipse Oxygen, JDK 8 and Maven.

2.2 Project Structure

Firstly, let’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!

Fig. 1: Application Project Structure
Fig. 1: Application Project Structure

2.3 Project Creation

This section will demonstrate on how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go toFile -> New -> Maven Project.

Fig. 2: Create Maven Project
Fig. 2: Create Maven Project

In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Select the ‘Create a simple project (skip archetype selection)’ checkbox and just click on next button to proceed.

Fig. 3: Project Details
Fig. 3: Project Details

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default:0.0.1-SNAPSHOT.

Fig. 4: Archetype Parameters
Fig. 4: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and apom.xml file will be created. It will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>Java8ConsumerSupplier</groupId><artifactId>Java8ConsumerSupplier</artifactId><version>0.0.1-SNAPSHOT</version><packaging>jar</packaging></project>

Developers can start adding the dependencies that they want. Let’s start building the application!

3. Application Building

Below are the steps involved in developing this application.

3.1 Java Class Creation

Let’s create the required Java files. Right-click on thesrc/main/java folder,New -> Package.

Fig. 5: Java Package Creation
Fig. 5: Java Package Creation

A new pop window will open where we will enter the package name as:com.jcg.java.

Fig. 6: Java Package Name (com.jcg.java)
Fig. 6: Java Package Name (com.jcg.java)

Once the package is created in the application, we will need to create theConsumer andSupplier classes to illustrate the implementation of these functional interfaces in Java8. Right-click on the newly created package:New -> Class.

Fig. 7: Java Class Creation
Fig. 7: Java Class Creation
Want to be a Java 8 Ninja ?
Subscribe to our newsletter and download the Java 8 FeaturesUltimateGuideright now!
In order to get you up to speed with the major Java 8 release, we have compiled a kick-ass guide with all the new features and goodies! Besides studying them online you may download the eBook in PDF format!

Thank you!

We will contact you soon.

A new pop window will open and enter the file name as:ConsumerTest. The consumer implementation class will be created inside the package:com.jcg.java.

Fig. 8: Java Class (ConsumerTest.java)
Fig. 8: Java Class (ConsumerTest.java)

Repeat the step (i.e. Fig. 7) and enter the filename as:SupplierTest. The supplier implementation class will be created inside the package:com.jcg.java.

Fig. 9: Java Class (SupplierTest.java)
Fig. 9: Java Class (SupplierTest.java)

3.1.1 Implementation of Consumer Class

To understand theaccept() method let’s take a look at the example below where I take a list of string values and print them using theprintList() method. Let’s have a look at a simple code example where theConsumer interface is being used.

ConsumerTest.java

package com.jcg.java;import java.util.function.Consumer;public class ConsumerTest {public static void main(String[] args) {System.out.println("E.g. #1 - Java8 Consumer Example\n");Consumer<String> consumer = ConsumerTest::printNames;consumer.accept("C++");consumer.accept("Java");consumer.accept("Python");consumer.accept("Ruby On Rails");}private static void printNames(String name) {System.out.println(name);}}

3.1.2 Implementation of Supplier Class

The supplier does the opposite of the consumer i.e. it takes no arguments but it returns some value by calling itsget() method. Do note, theget() method may return different values when it is being called more than once. Let’s have a look at a simple code example where theSupplier interface is being used.

SupplierTest.java

package com.jcg.java;import java.util.ArrayList;import java.util.List;import java.util.function.Supplier;public class SupplierTest {public static void main(String[] args) {System.out.println("E.g. #2 - Java8 Supplier Example\n");List<String> names = new ArrayList<String>();names.add("Harry");names.add("Daniel");names.add("Lucifer");names.add("April O' Neil");names.stream().forEach((item)-> {printNames(()-> item);});}private static void printNames(Supplier<String> supplier) {System.out.println(supplier.get());}}

Do remember, developers will have to use the ‘JDK 1.8‘ dependency for implementing the functional interfaces in their applications.

4. Run the Application

To run the application, right-click on theConsumerTest or theSupplierTest class,Run As -> Java Application. Developers can debug the example and see what happens after every step!

Fig. 9: Run Application
Fig. 9: Run Application

5. Project Demo

The application shows the following logs as output for theConsumer and theSupplier functional interfaces.

ConsumerTest.java

E.g. #1 - Java8 Consumer ExampleC++JavaPythonRuby On Rails

SupplierTest.java

E.g. #2 - Java8 Supplier ExampleHarryDanielLuciferApril O' Neil

That’s all for this post. Happy Learning!

6. Conclusion

In this tutorial, we looked what theConsumer<T> andSupplier<T> in-built interfaces are, defined in Java8, and what are their main advantage. I hope this article served developers whatever they were looking for.

7. Download the Eclipse Project

This was an example of Consumer and Supplier in Java8.

Download
You can download the full source code of this example here:Java8ConsumerSupplier
Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of YatinYatinJanuary 12th, 2018Last Updated: February 25th, 2019
2 1,165 5 minutes read
Photo of Yatin

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).

Related Articles

Bipartite Graph

Java not equal Example

January 17th, 2020
Bipartite Graph

Java API Tutorial

October 26th, 2020
Bipartite Graph

Java Struct Example

January 8th, 2020
Bipartite Graph

Java Node Example

November 20th, 2019
Bipartite Graph

Java Swing MVC Example

January 26th, 2016
Bipartite Graph

How to call a method in Java

December 26th, 2019
Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.