Lambda Syntax for Suppliers
What You'll Learn
You'll learn how to write Supplier<T> implementations using lambda expressions with the distinctive no-parameter syntax.
The Core Idea
Since Supplier<T> only has one method—get()—that takes no parameters and returns a value, its lambda syntax is unique: you start with empty parentheses (), followed by the arrow ->, and then the value expression.
Think of a Supplier like a vending machine button: you just press it (no input needed), and something comes out. The lambda captures this perfectly with its "no input, just output" structure.
Basic Lambda Syntax
// Full lambda syntax with type declaration
Supplier<String> greetingSupplier = () -> "Hello";
// The empty () represents "no parameters"
Supplier<Integer> numberSupplier = () -> 42;
// Multi-line body with explicit return
Supplier<Double> randomSupplier = () -> {
double value = Math.random();
return value * 100;
};
Why the Empty Parentheses Matter
The () isn't optional—it signals to Java that this lambda takes no parameters. Without it, Java wouldn't know whether you're writing a Supplier, a Function, or something else.
Supplier<String> message = () -> "No params!"; // Correct
Supplier<String> wrong = "No params!"; // Won't compile
Using Your Lambda Supplier
Supplier<String> lazyMessage = () -> "Generated on demand";
System.out.println(lazyMessage.get()); // Output: Generated on demand
Key Takeaway: Supplier lambdas always use the () -> expression pattern—empty parentheses for zero parameters, followed by the arrow and the value to supply.