Java8: deep dive to Supplier Interface



In this tutorial, we will learn How we can use a method reference as a Supplier and what we can do using this Supplier interface.


Supplier: To put it simply we use the term  Supplier when it produces something. So in terms of java Supplier is such an interface which takes no argument and produce a data type. This Data type can be any type <T>.

Java 8 create a concept called Functional Interface, Which is nothing but a Simple interface with one and only one abstract method.

Java 8 offers some inbuilt Functional Interfaces. The supplier is one of the inbuilt Functional interfaces which has only one abstract method called T get().

Please note that any interface(Custom) which has only one abstract method treated as a Functional interface in Java 8.


Let see the  Supplier Functional Interface in Java 8.

@FunctionalInterface
public interface Supplier<T> {

    /**
    * Gets a result.
    *
    * @return a result
    */
    T get();
}

So, Supplier is an Interface which takes no argument and returns any type (T) when invoked the get() function.

So we can say it is a kind of no args Lambda, which produces some type of value, This value can be a single value or collection of values depends on the implementation of lambda.

Now we will discuss how we can use Supplier in our program.

Constructor As a Supplier


One of the great features of Java 8 is method reference, we will talk about it in a later article but for now, By method reference, we can assign any method whose method signature match with any functional interface. Java 8 infer the type of functional interface when we pass method reference as a parameter or assign it to a functional interface.
We can use :: to use method reference instead of calling the same by . operator.

When I say by :: you can refer any method, I mean by it, it includes constructor also.
If we pay attention to the constructor which produces a class instance and takes nothing.
So it has the same signature as Supplier.



Let take a look How we can use Constructor as a supplier.

package com.example.supplier;

import java.util.ArrayList;
import java.util.function.Supplier;

public class LambdaASSupplier {
   
   Supplier<ArrayList> arryListSupplier = ArrayList::new;
   
   ArrayList produceArrayList(){
      return arryListSupplier.get();
   }
   
   

}


Here,  we refer the constructor using a method reference, so it returns a functional interface whose signature is same as Supplier, So we can reference the constructor using Supplier interface. By doing this we defer the ArrayList Object creation,  by new ArrayList() call we create an ArrayList Object instantly but using method reference we wrap constructor into an interface and execute the logic i.e create ArrayList when we call get method in the produceArrayList method.

Now we will try to make it generic,  we will try to create a method which will take any type of supplier and return specific type Object based on the supplier type.



package com.example.supplier;

import java.util.ArrayList;
import java.util.Date;
import java.util.function.Supplier;

public class LambdaASSupplier {
   
   public static <T> T  supplyElements(Supplier<T> supplier){
      return supplier.get();
   }
   
   public static void main(String[] args) {
      String s = LambdaASSupplier.supplyElements(String::new);
      ArrayList arraList = LambdaASSupplier.supplyElements(ArrayList::new);
      Date date = LambdaASSupplier.supplyElements(Date::new);
     
   }
   
   

}



We take Supplier<T> as an argument of supplyElements and returns T based on supplier type.

So we can say Constructor is a good candidate for supplying value, so we can refer constructor as a supplier and use the same to create Objects when the program needs it elsewher



Factory method as a Supplier :

Think about the factory method it is a static method which takes nothing but returns an Object so it is a potential candidate for Supplier interface, So we can use any factory method as a Supplier.

Let see a small example

package com.example.supplier;

public interface Shape {
   void display();

}

I have create a Shape interface which has a display method. Then I will create a Factory class which will produce different shapes.

Let see the Factory class

package com.example.supplier;

import java.util.function.Supplier;

public class ShapeFactory {
   
   public static Shape createRectangel(){
      return new Shape(){
          @Override
          public void display() {
              System.out.println(" I am a Rectangle");
             
          }
         
      };
     
   }
   
   public static Shape createSquare(){
      return new Shape(){
          @Override
          public void display() {
              System.out.println(" I am a Square");
             
          }
         
      };
     
   }
   
   public static void main(String[] args) {
      Supplier<Shape> recangleProducer = ShapeFactory::createRectangel;
      Supplier<Shape> squareProducer = ShapeFactory::createSquare;
     
      recangleProducer.get().display();
      squareProducer.get().display();
   }
   
   
   
   

}

Here I create two factory methods which will create a rectangle and Square shapes if you see the method signature of the factory method it is same as Supplier interface so easily we can reference this static factory method as a Supplier.

I did same in main method where I create two producer rectangle and square which are a supplier functional interface.

Later I create Rectangle or Square Object from that supplier.

We can also sophisticate our program , we can create a Factory of supplier


Let see that implementation

package com.example.supplier;

import java.util.function.Supplier;

public class ShapeProducerFactory {
   
   public static Supplier<Shape> createRectangleProducer()
   {
      return ShapeFactory::createRectangel;
   }
   
   public static Supplier<Shape> createsquareProducer()
   {
      return ShapeFactory::createSquare;
   }
   
   public static void main(String[] args) {
      ShapeProducerFactory.createRectangleProducer().get().display();
      ShapeProducerFactory.createsquareProducer().get().display();
   }

}

I just create a Factory of producers here which will produce the specific shape.


Conclusion: Supplier functions interface can be used as a reference of constructor, factory method so we can pass supplier interface as a  pointer of constructor or method, so we can invoke them later. In another place. So in a one-word Supplier interface give us the facility to pass producing behavior into a another method or as a variable so we can use that behavior later as a callback.

Post a Comment