Back to articles
Part-4 Functional Interface(Supplier)

Part-4 Functional Interface(Supplier)

via Dev.tos mathavi

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()); } } 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 = (nam

Continue reading on Dev.to

Opens in a new tab

Read Full Article
5 views

Related Articles