Core Java

Java 8 Consumer and Supplier Example

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

1. Introduction

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

1.1 What is Consumer?

Consumer<T> is an in-built functional interface introduced in Java8 in the java.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. Since Consumer 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 is T -> (). 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.

@FunctionalInterface
public 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 interface Consumer<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 the java.util.function package. The supplier can be used in all contexts where there is no input but an output is expected. Since Supplier 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 is T -> (). 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.

@FunctionalInterface
public 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 interface Supplier<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 the Consumer and Supplier 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 to File -> 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 a pom.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 the src/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 the Consumer and Supplier 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

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 the accept() method let’s take a look at the example below where I take a list of string values and print them using the printList() method. Let’s have a look at a simple code example where the Consumer 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 its get() method. Do note, the get() method may return different values when it is being called more than once. Let’s have a look at a simple code example where the Supplier 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 the ConsumerTest or the SupplierTest 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 the Consumer and the Supplier functional interfaces.

ConsumerTest.java

E.g. #1 - Java8 Consumer Example

C++
Java
Python
Ruby On Rails

SupplierTest.java

E.g. #2 - Java8 Supplier Example

Harry
Daniel
Lucifer
April O' Neil

That’s all for this post. Happy Learning!

6. Conclusion

In this tutorial, we looked what the Consumer<T> and Supplier<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

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).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Rodrigo Chappa
Rodrigo Chappa
5 years ago

I think the description “Supplier’s Function Descriptor is T -> ().” should be
“Supplier’s Function Descriptor is () -> T. “, Otherwise it is describing a consumer.

S hshs
S hshs
5 years ago

nice article.
“Supplier’s Function Descriptor is T -> ()” is incorrect as mentioned by Rodrigo

Back to top button