Course Content
Stream API
Stream API
Supplier: Data Generation
Here's how the Supplier
functional interface is implemented:
The key responsibility of the get()
method is to return an object of type T
without taking any parameters.
Practical Use of Supplier
Supplier
is often used in situations where data needs to be generated on demand. This can be useful for lazy initialization, generating random values, or retrieving values from an external source.
Let's create a system that generates random passwords. Using the Supplier
functional interface, you can easily organize password generation on request.
Main
package com.example; import java.util.Random; import java.util.function.Supplier; public class Main { public static void main(String[] args) { // Supplier for generating random passwords Supplier<String> passwordSupplier = () -> { String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()"; StringBuilder password = new StringBuilder(); Random random = new Random(); for (int i = 0; i < 12; i++) { int index = random.nextInt(characters.length()); password.append(characters.charAt(index)); } return password.toString(); }; // Generate and print the random password String generatedPassword = passwordSupplier.get(); System.out.println("Generated password: " + generatedPassword); } }
You create a Supplier
that generates a random password of 12 characters. The lambda expression inside the Supplier
uses the Random
class to select random characters from a string.
The get()
method triggers this password generation logic only when needed, enabling lazy generation of values.
Lazy Generation
Initially, you create the Supplier
, but the code inside it doesn't execute immediately. This is an important feature. Instead of executing some logic right away (e.g., generating a password), you simply record it inside the Supplier
as an instruction to be executed later when required.
Here, the code inside the Supplier
(password generation) doesn't execute immediately. Instead, you're saying, "When someone asks, this is how you'll generate the password." Now, when you call get()
on this Supplier
:
Only then does the code inside the Supplier
execute, and the password is generated. This is lazy execution.
Key Responsibilities
1. What does the Supplier
interface do in Java?
2. What happens if you call the get()
method twice on the same Supplier
object?
Thanks for your feedback!