Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

A Look at Java 8's Supplier and Consumer Interfaces

DZone's Guide to

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.

· Java Zone
Free Resource

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

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!

Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat

Topics:
java ,java 8 ,functional interface ,supplier ,consumer ,tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}