DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Why Haven’t You Upgraded to HTTP/2?
  • Advanced Brain-Computer Interfaces With Java
  • Simplify Java: Reducing Unnecessary Layers and Interfaces [Video]
  • Mastering Backpressure in Java: Concepts, Real-World Examples, and Implementation

Trending

  • Issue and Present Verifiable Credentials With Spring Boot and Android
  • AI, ML, and Data Science: Shaping the Future of Automation
  • Java Virtual Threads and Scaling
  • Evolution of Cloud Services for MCP/A2A Protocols in AI Agents
  1. DZone
  2. Coding
  3. Java
  4. A Look at Java 8's Supplier and Consumer Interfaces

A Look at Java 8's Supplier and Consumer Interfaces

These two functional interfaces are good to have in your toolkit. Let's dive into the Supplier and Consumer interfaces and their associated methods to see how they work.

By 
Arun Pandey user avatar
Arun Pandey
DZone Core CORE ·
Apr. 11, 17 · Tutorial
Likes (19)
Comment
Save
Tweet
Share
224.9K Views

Join the DZone community and get the full member experience.

Join For Free

java.util.function.Supplier is a functional interface. As per the definition of functional interfaces, it has one abstract functional method T get().

Editing: “Supplier and Consumer Interface in Java8”

Javadoc Definition

Functional Interface: This is a functional interface and can, therefore, be used as the assignment target for a lambda expression or method reference. Instances of functional interfaces can be created with lambda expressions, method references, or constructor references.

The Supplier interface signature is as below, which represents a supplier of results.

Editing: “Supplier and Consumer Interface in Java8”

@FunctionalInterface

public interface Supplier

Editing: “Supplier and Consumer Interface in Java8”

Here, T is the type of results supplied by this supplier.

Editing: “Supplier and Consumer Interface in Java8”

Method Definition as per the Javadoc

Editing: “Supplier and Consumer Interface in Java8”

T get(): This abstract method does not accept any argument but instead returns newly generated values, T, in the stream. But there is no requirement that new or distinct results be returned each time the supplier is invoked.

Now, let's look at an example.

Person.java

package com.test.java8;

public class Person {
    private String name;
    private int age;
    private String address;

    public Person(String name, int age, String address) {
        this.name = name;
        this.age = age;
        this.address = address;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getAddress() {
        return address;
    }
    public void setDesignation(String address) {
        this.address = address;
    }
}
Editing: “Supplier and Consumer Interface in Java8”


Person.java is a bean class, which we will use to supply the data using Supplier in the TestSupplier class below.

TestSupplier.java

package com.test.java8;
import java.util.function.Supplier;

public class TestSupplier {
    public static void main(String[] args) {
        Supplier < Person > supplier = () - > {
            return new Person("Varun", 30, "Programmer");
        };
        Person p = supplier.get();
        System.out.println("Person Detail:\n" + p.getName() + ", " + p.getAge() + ", " + p.getAddress());
    }
}
Editing: “Supplier and Consumer Interface in Java8”


There are primitive specializations of the Supplier interface:

  • IntSupplier having one abstract method getAsInt()
  • LongSupplier having one abstract method getAsLong()
  • DoubleSupplier having one abstract method getAsDouble()
  • BooleanSupplier having one abstract method getAsBoolean()
Editing: “Supplier and Consumer Interface in Java8”

Consumer Interface

java.util.function.Consumer is a functional interface. Like Supplier, it has one abstract functional method accept(T t)and a default method andThen(Consumer<? super T> after)

Editing: “Supplier and Consumer Interface in Java8”

Note: Default methods are not abstract methods.

Editing: “Supplier and Consumer Interface in Java8”

The Consumer interface signature is as below, which represents an operation that accepts a single input argument and returns no result.

@FunctionalInterface

public interface Consumer

Here, T is the type of the input to the operation.

Editing: “Supplier and Consumer Interface in Java8”

Method Definition as per Javadoc

void accept(T t): This abstract method takes one argument and performs this operation on the given argument. It doesn't return any value.

Editing: “Supplier and Consumer Interface in Java8” Editing: “Supplier and Consumer Interface in Java8”

default Consumer<T> andThen(Consumer<? super T> after) :

default Consumer < T > andThen(Consumer << ? super T > after) {
    Objects.requireNonNull(after);
    return (T t) - > {
        accept(t);after.accept(t);
    };
}
Editing: “Supplier and Consumer Interface in Java8”


This 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.

Editing: “Supplier and Consumer Interface in Java8”

Let's look at an example:

package com.test.java8;
import java.util.function.Consumer;

public class TestConsumer {
    public static void main(String[] args) {
        Consumer < String > consumer1 = (arg) - > {
            System.out.println(arg + "OK");
        };
        consumer1.accept("TestConsumerAccept - ");
        Consumer < String > consumer2 = (x) - > {
            System.out.println(x + "OK!!!");
        };
        consumer1.andThen(consumer2).accept("TestConsumerAfterThen - ");
    }
}
Editing: “Supplier and Consumer Interface in Java8”


Again, like Supplier, here are some primitive specializations of Consumer interface:

  • IntConsumer having one abstract method ' accept(int)' and one default method ' default IntConsumer andThen(IntConsumer after)'
  • DoubleConsumer having one abstract method ' accept(double)' and one default method ' default DoubleConsumer andThen(DoubleConsumer after)'
  • LongConsumer having one abstract method ' accept(long)' and one default method ' default LongConsumer andThen(LongConsumer after)'

Happy learning!

Interface (computing) consumer Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Why Haven’t You Upgraded to HTTP/2?
  • Advanced Brain-Computer Interfaces With Java
  • Simplify Java: Reducing Unnecessary Layers and Interfaces [Video]
  • Mastering Backpressure in Java: Concepts, Real-World Examples, and Implementation

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!