Supplier Functional Interface in Java


Supplier Functional Interface:-

Supplier is an in-built functional interface which can be used in all contexts where there is no input but an output is expected.
In other words, we can say that if no input is required, but we need some result by performing some operation then we use Supplier functional Interface.
Common example of such an operation is retrieving records from database and returning them or performing some calculation and returning some value.

Supplier functional interface members:-

1) The Supplier interface has a SAM called get( ).
2) It doesn't accept any argument but returns an object of an object of any datatype.
3) Supplier contains only one method and it is:- get( );
4) The method get( ) is an abstract method.

Prototype of get( ):- Following is the complete prototype of the method get( ) as declared in the interface Supplier.

       public interface Supplier<T>  {
                public <T> get( );
       }

As we can observe the method get( ) accepts nothing as argument but returns a value of type T.

Example:-

Program to returns a random integer using Supplier functional Interface.


import java.util.Random;
import java.util.function.Supplier;
public class Example1 {
    public static void main(String[] args) {
       Supplier<Integer> s=()->{
            Random r=new Random();
            int n=r.nextInt(100);
            return n;
     };
        System.out.println("First Random number: "+s.get());
        System.out.println("Second Random number: "+s.get()); 
    }   

}

Output:-

First Random number: 41
Second Random number: 54

Post a Comment

0 Comments