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
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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

  • DevOps and Platform Engineering Readiness Checklist: Everything Needed for a Scalable, Secure, High-Velocity Delivery Platform
  • Stop Running Two Data Systems for One Agent Query
  • Designing API-First EMR Architectures in .NET: Enabling Modular Growth in Compliance-Driven Systems
  • Architecting an Embedded Efficiency Layer: A Platform Deep Dive into Day-Two Operational Tuning
  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
225.3K 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

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

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook