Over a million developers have joined DZone.

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

· Java Zone

Learn more about how the Java language, tools and frameworks have been the foundation of countless enterprise systems, brought to you in partnership with Salesforce.

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


Discover how the Force.com Web Services Connector (WSC) is a code-generation tool and runtime library for use with Force.com Web services, brought to you in partnership with Salesforce.


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

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}