DEV Community

Cover image for Part-4 Functional Interface(Supplier)
s mathavi
s mathavi

Posted on

Part-4 Functional Interface(Supplier)

Supplier:

  • A functional interface in java.util.function.
  • Represents a value provider: it returns a value but takes no input.

Core method:

T get()

Key Characteristics:

Opposite of Consumer:

Consumer → takes input, no return.
Supplier → no input, returns output.

Often used for lazy initialization, default values, or generating data (like random numbers, timestamps, IDs).

Example: Basic Supplier

import java.util.function.Supplier;
public class SupplierDemo {
    public static void main(String[] args) {

        // Supplier that generates a random number
        Supplier<Double> randomSupplier = () -> Math.random();

        // Each call to get() produces a new value
        System.out.println("Random 1: " + randomSupplier.get());
        System.out.println("Random 2: " + randomSupplier.get());
    }
}
Enter fullscreen mode Exit fullscreen mode

Example: Supplier for Default Value

import java.util.function.Supplier;

public class DefaultValueDemo {
    public static void main(String[] args) {

        Supplier<String> defaultName = () -> "Unknown User";

        String name = null;
        String finalName = (name != null) ? name : defaultName.get();

        System.out.println("Name: " + finalName); // Output: Name: Unknown User
    }
}
Enter fullscreen mode Exit fullscreen mode

Specialized Suppliers:

Java also provides primitive-specialized suppliers:

  • IntSupplier → returns int.
  • LongSupplier → returns long.
  • DoubleSupplier → returns double.

Example:

import java.util.function.IntSupplier;

public class IntSupplierDemo {
    public static void main(String[] args) {
        IntSupplier diceRoll = () -> (int)(Math.random() * 6) + 1;
        System.out.println("Dice rolled: " + diceRoll.getAsInt());
    }
}
Enter fullscreen mode Exit fullscreen mode

Thanks for reading — talk to you soon.

Top comments (0)