Over a million developers have joined DZone.

Supplier Interface in java.util.function Package in Java 8

DZone's Guide to

Supplier Interface in java.util.function Package in Java 8

· Java Zone
Free Resource

Learn how to troubleshoot and diagnose some of the most common performance issues in Java today. Brought to you in partnership with AppDynamics.

In my previous posts I wrote about Predicate, Consumer and Function interfaces. In this post I will write about Supplier interface with which I will conclude the description of the interfaces in the java.util.function package. Though there are many other interfaces in that package, but the interfaces I have explained form the crux of the other interfaces.

The javadoc for Supplier interface states:

A supplier of objects. The result objects are either created during the invocation of get() or by some prior action.

And the sole method in this interface is get() which should return an object of the declared type.

To understand the usage of this interface, lets consider 2 classes- Vehicle and Car defined as:

class Vehicle{
  public void drive(){ 
    System.out.println("Driving vehicle ...");
class Car extends Vehicle{
  public void drive(){
    System.out.println("Driving car...");

And lets consider a static method which invokes the drive() method on the instance of Vehicle or Car:

public class SupplierDemo {   
  static void driveVehicle(Supplier<? extends Vehicle> supplier){
    Vehicle vehicle = supplier.get();

And to invoke the above driveVehicle method, we should provide an implementation of the Supplier interface which we can do by passing in a lambda expression. Lets look at the code:

public static void main(String[] args) {
  //Using Lambda expression
  driveVehicle(()-> new Vehicle());
  driveVehicle(()-> new Car());
  //Using method expression

The first two invocations are familiar to the readers of my blog, but the other two are something new and those are called as “Method Expression“. Soon I will write about method expression but if you are curious to know about it, you can read about it here under the section: “8. Method Expression“.


Understand the needs and benefits around implementing the right monitoring solution for a growing containerized market. Brought to you in partnership with AppDynamics.


Published at DZone with permission of Mohamed Sanaulla, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}