Introduction
Java Supplier is one of the most important Functional Interfaces introduced in Java 8 as part of the java.util.function package. Unlike other functional interfaces such as Predicate, Consumer, and Function, a Supplier does not accept any input arguments. Instead, its primary responsibility is to generate and return a value whenever it is called.
The name “Supplier” itself indicates its purpose—it supplies or produces data on demand. The returned value can be a simple object, a random number, the current date and time, a database connection, or even a complex custom object.
Before Java 8, developers often created separate utility methods or anonymous classes to generate values. With the introduction of Lambda Expressions and Functional Interfaces, Java Supplier provides a cleaner, more concise, and reusable approach for generating data.
For example, suppose you want to generate the current date.
Without Supplier:
public class Main {
public static String getDate() {
return java.time.LocalDate.now().toString();
}
public static void main(String[] args) {
System.out.println(getDate());
}
}
Using Supplier:
import java.time.LocalDate;
import java.util.function.Supplier;
public class Main {
public static void main(String[] args) {
Supplier supplier =
() -> LocalDate.now();
System.out.println(supplier.get());
}
}
Output
The Supplier interface is commonly used with Streams, Optional, Lazy Initialization, Object Factories, Dependency Injection, and Caching.
In this tutorial, you’ll learn everything about Java Supplier, including syntax, methods, examples, real-life applications, advantages, limitations, common mistakes, best practices, and interview questions.
What is Java Supplier?
A Supplier is a Functional Interface that accepts no input arguments and returns a value.
It is defined as:
@FunctionalInterface
public interface Supplier {
T get();
}
Here:
- T represents the return type.
- get() generates and returns a value.
- It does not accept any parameters.
Suppliers are commonly used for:
- Creating objects
- Generating random numbers
- Returning current date and time
- Lazy initialization
- Loading configuration values
- Creating default values
Why Do We Need Supplier?
Before Java 8:
public static int generateNumber() {
return new java.util.Random().nextInt(100);
}
Using Supplier:
Supplier randomNumber =
() -> new java.util.Random().nextInt(100);
Benefits include:
- Less boilerplate code
- Better readability
- Reusable logic
- Supports functional programming
- Easy integration with Stream API
Features of Supplier
Some important features are:
- Introduced in Java 8
- Part of java.util.function
- Functional Interface
- Accepts no parameters
- Returns a value
- Works with Lambda Expressions
- Supports Method References
- Ideal for lazy evaluation
- Integrates with Optional and Streams
- Encourages reusable code
Syntax
General syntax:
Supplier supplier = () -> {
return value;
};
Simplified syntax:
Supplier supplier =
() -> "Hello Java";
Using the supplier:
System.out.println(supplier.get());
Output
The get() Method
The primary method of Supplier is:
T get()
Example:
import java.util.function.Supplier;
public class Main {
public static void main(String[] args) {
Supplier supplier =
() -> "Java Programming";
System.out.println(supplier.get());
}
}
Output
Example 1: Generate a Random Number
import java.util.Random;
import java.util.function.Supplier;
public class Main {
public static void main(String[] args) {
Supplier random =
() -> new Random().nextInt(100);
System.out.println(random.get());
}
}
Output
Example 2: Current Date
import java.time.LocalDate;
import java.util.function.Supplier;
public class Main {
public static void main(String[] args) {
Supplier today =
LocalDate::now;
System.out.println(today.get());
}
}
Output
Example 3: Create an Object
import java.util.function.Supplier;
class Student {
Student() {
System.out.println("Student Created");
}
}
public class Main {
public static void main(String[] args) {
Supplier supplier =
Student::new;
supplier.get();
}
}
Output
Example 4: Default Value
import java.util.function.Supplier;
public class Main {
public static void main(String[] args) {
Supplier city =
() -> "Delhi";
System.out.println(city.get());
}
}
Output
Supplier with Optional
The Optional.orElseGet() method accepts a Supplier.
Example:
import java.util.Optional;
public class Main {
public static void main(String[] args) {
Optional optional =
Optional.empty();
String result =
optional.orElseGet(() -> "Default Value");
System.out.println(result);
}
}
Output
Supplier with Stream API
The Stream.generate() method uses a Supplier to produce elements.
Example:
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
Stream.generate(() -> "Java")
.limit(3)
.forEach(System.out::println);
}
}
Output
Java
Java
Supplier vs Consumer
| Supplier | Consumer |
|---|---|
| Accepts no input | Accepts one input |
| Returns a value | Returns nothing |
| Method: get() | Method: accept() |
| Generates data | Processes data |
Supplier vs Function
| Supplier | Function |
|---|---|
| No input parameter | Accepts one input parameter |
| Returns a value | Returns a transformed value |
| Method: get() | Method: apply() |
Supplier vs Predicate
| Supplier | Predicate |
|---|---|
| Returns any type | Returns boolean |
| No input | One input |
| Generates values | Tests conditions |
Real-life Example
Imagine an Online Shopping System that generates unique order IDs whenever a new order is created.
import java.util.UUID;
import java.util.function.Supplier;
public class Main {
public static void main(String[] args) {
Supplier orderId =
() -> UUID.randomUUID().toString();
System.out.println(orderId.get());
}
}
Output
Other real-world applications include:
- Creating database connections
- Generating session IDs
- Creating timestamps
- Lazy loading objects
- Configuration providers
- Object factories
- Token generation
- Cache initialization
Advantages of Supplier
- Reduces boilerplate code
- Easy to understand
- Supports lazy evaluation
- Encourages reusable code
- Integrates with Stream API
- Works with Optional
- Supports Method References
- Improves readability
Limitations
- Cannot accept input parameters.
- Produces only one value per invocation.
- Not suitable for processing existing data.
- Complex generation logic should be moved into dedicated methods or services.
Common Mistakes
1. Trying to Pass Parameters
Incorrect:
Supplier supplier =
number -> number * 2;
A Supplier cannot accept parameters.
Correct:
Supplier supplier =
() -> 20;
2. Forgetting to Call get()
Incorrect:
Supplier supplier =
() -> "Java";
System.out.println(supplier);
Correct:
System.out.println(supplier.get());
3. Using Supplier for Data Processing
Incorrect:
Supplier supplier =
() -> "Java".toUpperCase();
Although this compiles, if you’re transforming existing input data, a Function is usually the more appropriate choice. Use Supplier when the value is generated independently of any input.
4. Creating Expensive Objects Repeatedly
If object creation is costly, avoid calling get() multiple times unnecessarily. Cache or reuse the generated object when appropriate.
5. Writing Complex Lambda Expressions
Keep Supplier implementations concise. For lengthy logic, delegate to a separate method and reference it using a Method Reference where possible.
Best Practices
- Use Supplier when no input is required.
- Keep supplier logic simple and focused.
- Prefer Method References when appropriate (for example, LocalDate::now).
- Use Supplier for lazy initialization.
- Combine Supplier with Optional.orElseGet() for efficient default value creation.
- Use Stream.generate() for creating infinite streams.
- Avoid performing heavy operations repeatedly inside get() unless necessary.
Time Complexity
The complexity depends on the implementation inside the Supplier.
| Operation | Time Complexity |
|---|---|
| get() (constant value) | O(1) |
| No input | O(1) |
| Generates values | O(1) |
| No input | O(1) |
| Generates values | O(n) (for generating n elements) |
Conclusion
Java Supplier is a powerful Functional Interface introduced in Java 8 that represents a source of data. Unlike Predicate, Consumer, and Function, it accepts no input and simply supplies a value when requested. Supplier is widely used for lazy initialization, object creation, default value generation, random value generation, and integration with the Stream API and Optional.
By understanding the get() method, common use cases, best practices, and real-world applications, you can write cleaner, more efficient, and more maintainable Java code. Mastering the Supplier interface is an important step toward understanding Java’s functional programming model and is a frequently tested topic in Java technical interviews.