๐ŸŽ‰ Special Offer !    Code: GET300OFF    Flat โ‚น300 OFF on every Java Course
Grab Deal ๐Ÿš€

Supplier Interface  


Introduction
  • Supplier interface is a functional interface in Java 8 that represents a supplier of results and takes no input arguments.
  • It is part of the java.util.function package.
  • Uses of Supplier Interface:
    • Used to generate or supply data without any input.
    • Commonly used for lazy evaluation or on-demand object creation.
    • Helpful in returning default values when data is not available.
    • Mostly used in Stream.generate() and similar factory-style methods.
  • Syntax :
    public interface Supplier
    {
        T get();
        //no other abstract methods
    }
Programs:
  • 1. Simple program without lambda expression:
    import java.util.function.Supplier;
    
    public class MainApp
    {
        public static void main(String[] args)
        {
            // Supplier to provide a random number using anonymous class
            Supplier<Double> randomNumber = new Supplier<Double>() {
                @Override
                public Double get() {
                    return Math.random();
                }
            };
    
            // Get numbers
            System.out.println("Random Number 1 : " + randomNumber.get());
            System.out.println("Random Number 2 : " + randomNumber.get());
        }
    }
  • 2. Program with lambda expression:
    import java.util.function.Supplier;
    
    public class MainApp
    {
        public static void main(String[] args)
        {
            // Supplier to provide a random number using lambda expression
            Supplier<Double> randomNumber = () -> Math.random();
    
            // Get numbers
            System.out.println("Random Number 1 : " + randomNumber.get());
            System.out.println("Random Number 2 : " + randomNumber.get());
        }
    }