Supplier Interface in Java with Examples
A supplier interface in Java is a functional interface defined in the java.util.function package. It represents a supplier of results, i.e., a function that doesn't take any arguments but produces a result of a specified type. The supplier interface is defined as follows:
@FunctionalInterface public interface Supplier<T> { T get(); }
The Supplier interface is often used in scenarios where you need to generate or provide values on demand without taking any input.
Example 1
In the above code, we create a Supplier using a lambda expression. The Supplier generates a random number between 0 and 100 using the Math.random() method. The get() method is called on the Supplier to obtain the generated random number, which is then printed to the console.
FileName: SupplierExample.java
import java.util.function.Supplier; public class SupplierExample { public static void main(String[] args) { // Create a Supplier that generates a random number Supplier<Integer> randomNumberSupplier = () -> (int) (Math.random() * 100); // Generate and print a random number int randomNumber = randomNumberSupplier.get(); System.out.println("Random number: " + randomNumber); } }
Output
Random number: 71
Example 2
The above Java program generates and displays the current timestamp. It utilizes the LocalDateTime class from the java.time package and the Supplier functional interface from the java.util.function package. The program begins by importing the necessary classes: LocalDateTime and Supplier. LocalDateTime enables manipulation and representation of dates and times, while Supplier represents a supplier of results.
FileName: TimestampGenerator.java
import java.time.LocalDateTime; import java.util.function.Supplier; public class TimestampGenerator { public static void main(String[] args) { // Create a supplier that generates the current timestamp Supplier<LocalDateTime> timestampSupplier = LocalDateTime::now; // Get the current timestamp using the supplier LocalDateTime timestamp = timestampSupplier.get(); // Print the current timestamp System.out.println("Current timestamp: " + timestamp); } }
Output
Current timestamp: 2023-07-10T15:47:47.564009346
Example 3
In the above code, we create three instances of the Supplier interface. In the first example, we use a lambda expression to supply a constant string value. In the second example, we use a method reference to supply a random number between 0.0 and 1.0. In the third example, we use a lambda expression to build a Person object using the Person constructor. We then invoke the get() method on each Supplier instance to obtain the supplied result and print it to the console.
FileName: SupplierExample.java
import java.util.function.Supplier; public class SupplierExample { public static void main(String[] args) { // Example 1: Supplying a constant value Supplier<String> supplier1 = () -> "Hello, world!"; String result1 = supplier1.get(); System.out.println(result1); // Output: Hello, world! // Example 2: Generating a random number Supplier<Double> randomSupplier = Math::random; double result2 = randomSupplier.get(); System.out.println(result2); // Output: A random number between 0.0 and 1.0 // Example 3: Building an object using a supplier Supplier<Person> personSupplier = () -> new Person("Ram", 22); Person person = personSupplier.get(); System.out.println(person.getName()); System.out.println(person.getAge()); } } class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } }
Output
Hello, world! 0.1623169941147472 Ram 22
Example 4
In the above code, we create a Supplier instance that generates a unique ID by combining the current time in milliseconds and a random number. Every time we invoke the get() method on this supplier, it generates a new unique ID.
FileName: SupplierExample.java
import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; public class SupplierExample { public static void main(String[] args) { // Example 1: Generating a unique ID Supplier<String> idSupplier = () -> { // Generate a unique ID using a combination of current time and a random number long currentTime = System.currentTimeMillis(); int randomNumber = (int) (Math.random() * 1000); return "ID-" + currentTime + "-" + randomNumber; }; String uniqueId = idSupplier.get(); System.out.println(uniqueId); } }
Output
ID-1689004127512-387
Example 5
In the above code, we have two scenarios:
- Supplying a random quote: We create a Supplier instance that supplies a random quote from an array of quotes. Each time we invoke the get() method on the supplier, it selects a random quote and returns it.
- Supplying a database connection: We create a Supplier instance that supplies a DatabaseConnection object by calling the constructor. The get() method on the supplier returns a new instance of DatabaseConnection.
FileName: SupplierExample5.java
import java.util.function.Supplier; public class SupplierExample5 { public static void main(String[] args) { // Example 1: Supplying a random quote Supplier<String> quoteSupplier = () -> { String[] quotes = { "Be yourself; everyone else is already taken.", "In three words I can sum up everything I've learned about life: it goes on.", "The only way to do great work is to love what you do.", "You miss 100% of the shots you don't take." }; int randomIndex = (int) (Math.random() * quotes.length); return quotes[randomIndex]; }; String randomQuote = quoteSupplier.get(); System.out.println(randomQuote); // Example 2: Supplying a database connection Supplier<DatabaseConnection> connectionSupplier = DatabaseConnection::new; DatabaseConnection connection = connectionSupplier.get(); connection.connect(); // Use the database connection... } } class DatabaseConnection { public void connect() { // Perform connection logic System.out.println("Connected to the database."); } }
Output
In three words I can sum up everything I've learned about life: it goes on. Connected to the database.